python之tkinter使用

  基础控件

import tkinter as tk
from tkinter import ttk


def func():
    print(input_text.get())


def getCheckButtonVals():
    message = ""
    if hobby1.get() == True:
        message += "money\n"
    if hobby2.get() == True:
        message += "power\n"
    if hobby3.get() == True:
        message += "people\n"

    # 清空text中所有内容
    text2.delete(0.0, tk.END)
    text2.insert(tk.INSERT, message)


def getRadioButtonVals():
    print(choice.get())


# 创建主窗口
win = tk.Tk()
# 设置标题
win.title("demo")
# 设置大小和位置
win.geometry("1500x500+100+50")


# 标签控件,可以显示文本
# win:父窗体,text:显示的文本内容,bg:背景色,fg:字体颜色,font:字体
# wraplength:超过指定文本宽度后换行,justify:换行后的对齐方式,anchor:位置 n北 e东 w西 s南 center居中 ne东北方向
label = tk.Label(
    win, text="this is a word", bg="silver", fg="black", font=("黑体", 14), width=10, height=2, wraplength=100, justify="left", anchor="center"
)
# 布局
label.pack(side=tk.LEFT, padx=5, pady=5)


# 按钮
button1 = tk.Button(win, text="按钮", command=func, width=10, height=2)
button1.pack()
button2 = tk.Button(win, text="按钮", command=lambda: print("按钮2"))
button2.pack()
button3 = tk.Button(win, text="退出", command=win.quit)
button3.pack()


# 单选框
choice = tk.IntVar()
radio1 = tk.Radiobutton(win, text="one", value=1, variable=choice, command=getRadioButtonVals)  # 单选框
radio1.pack()
radio2 = tk.Radiobutton(win, text="two", value=2, variable=choice, command=getRadioButtonVals)
radio2.pack()


# 多选框
hobby1 = tk.BooleanVar()
check1 = tk.Checkbutton(win, text="money", variable=hobby1, command=getCheckButtonVals)  # 多选框
check1.pack()
hobby2 = tk.BooleanVar()
check2 = tk.Checkbutton(win, text="power", variable=hobby2, command=getCheckButtonVals)
check2.pack()
hobby3 = tk.BooleanVar()
check3 = tk.Checkbutton(win, text="people", variable=hobby3, command=getCheckButtonVals)
check3.pack()


# 输入控件
entry1 = tk.Entry(win, show="*")  # 输入控件,用于显示简单的文本内容。 show="*" 可以表示输入密码,密文显示
entry1.pack()
input_text = tk.Variable()  # 绑定变量
entry2 = tk.Entry(win, textvariable=input_text)
entry2.pack()
input_text.set("hello")  # 设置值
print(input_text.get())  # 取值
print(entry2.get())


# 文本控件
text = tk.Text(win, width=50, height=5)  # :用于显示多行文本,height表示的是显示的行数
text.pack()
str = """long text"""
text.insert(tk.INSERT, str)
# 文本控件带滚动条
scroll = tk.Scrollbar()  # 创建滚动条
text2 = tk.Text(win, width=50, height=3)
scroll.pack(side=tk.RIGHT, fill=tk.Y)  # side放到窗体的哪一侧,  fill填充
text2.pack(side=tk.LEFT, fill=tk.Y)
scroll.config(command=text2.yview)  # 关联
text2.config(yscrollcommand=scroll.set)
text2.insert(tk.INSERT, str)


# 列表框
# selectmode:BROWSE
# selectmode:SINGLE 与BORWSE相似,但是不支持鼠标按下后移动选中位置
# selectmode:EXTENDED:可以使listbox支持shift和Ctrl
# selectmode:MULTIPLE 支持多选
selected = tk.StringVar()
lb = tk.Listbox(win, selectmode=tk.BROWSE, listvariable=selected)
lb.pack()
for item in ["good", "nice", "handsome", "aaa", "bbb", "ccc", "ddd"]:
    lb.insert(tk.END, item)  # 按顺序添加
lb.insert(tk.ACTIVE, "cool")  # 在开始添加
lb.insert(tk.END, *["very good", "very nice"])  # 将列表当做一个元素添加
lb.delete(5, 6)  # 删除:参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只删除第一个索引处的内容
lb.select_set(2, 3)  # 选中:参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只选中第一个索引处的内容
lb.select_clear(2)  # 取消选中:参数1为开始的索引,参数2为结束的索引,如果不指定参数2,只取消第一个索引处的内容
print(lb.size())  # 获取到列表中的元素个数
print(lb.get(2, 3))  # 获取值
print(lb.curselection())  # 返回当前的索引项,不是item元素
print(lb.selection_includes(3))  # 判断:一个选项是否被选中


# 下拉菜单
cv = tk.StringVar()
com = ttk.Combobox(win, textvariable=cv)
com.pack()
com["value"] = ("黑龙江", "吉林", "辽宁")  # 设置下拉数据
com.current(0)  # 设置默认值


# 滑块
# orient:方向,HORIZONTAL,VERTICAL(默认);length:水平时表示宽度,竖直时表示高度
scale1 = tk.Scale(win, from_=0, to=100, orient=tk.HORIZONTAL, tickinterval=10, length=200)
scale1.pack()
scale1.set(20)  # 设置值
print(scale1.get())  # 取值


# sp = tk.Spinbox(win, from_=0, to=100, increment=5)
sp = tk.Spinbox(win, values=(0, 2, 4, 6, 8))
sp.pack()
print(sp.get())  # 取值



# 框架控件:在桌面上显示一个矩形区域,多作为一个容器控件
frm = tk.Frame(win)
frm.pack(side=tk.LEFT)
frm_l = tk.Frame(frm)  # left
tk.Label(frm_l, text="用户名:").pack(side=tk.TOP)
tk.Label(frm_l, text="密码:").pack(side=tk.TOP)
frm_l.pack(side=tk.LEFT)
frm_r = tk.Frame(frm)  # right
tk.Entry(frm_r).pack(side=tk.TOP)
tk.Entry(frm_r, show="*").pack(side=tk.TOP)
frm_r.pack(side=tk.RIGHT)


# 表格
table = ttk.Treeview(win)
table.pack()
table["columns"] = ("姓名", "年龄", "身高", "体重")  # 定义列
table.column("姓名", width=100)  # 设置列
table.column("年龄", width=100)
table.column("身高", width=100)
table.column("体重", width=100)
table.heading("姓名", text="姓名-name")  # 设置表头
table.heading("年龄", text="年龄-age")
table.heading("身高", text="身高-height")
table.heading("体重", text="体重-weight")
table.insert("", 0, text="line1", values=("小郑", "34", "177cm", "70kg"))  # 添加数据
table.insert("", 1, text="line2", values=("小张", "43", "188cm", "90kg"))

# 树
tree = ttk.Treeview(win)
tree.pack()
treeF1 = tree.insert("", 0, "中国", text="中国Chi", values=("F1"))  # 添加一级树枝
treeF2 = tree.insert("", 1, "美国", text="美国USA", values=("F1"))
treeF3 = tree.insert("", 2, "英国", text="英国UK", values=("F1"))
treeF1_1 = tree.insert(treeF1, 0, "黑龙江", text="中国黑龙江", values=("F1_1"))  # 二级树枝
treeF1_2 = tree.insert(treeF1, 1, "吉林", text="中国吉林", values=("F1_2"))
treeF1_3 = tree.insert(treeF1, 2, "辽宁", text="中国辽宁", values=("F1_3"))
treeF2_1 = tree.insert(treeF2, 0, "aaa", text="aaaa", values=("F2_1"))
treeF2_2 = tree.insert(treeF2, 1, "bbb", text="bbbb", values=("F2_2"))
treeF2_3 = tree.insert(treeF2, 2, "ccc", text="cccc", values=("F2_3"))
treeF1_1_1 = tree.insert(treeF1_1, 0, "哈尔滨", text="黑龙江哈尔滨")  # 三级树枝
treeF1_1_2 = tree.insert(treeF1_1, 1, "五常", text="黑龙江五常")


# 进入消息循环
win.mainloop()

布局

import tkinter as tk

win = tk.Tk()
win.title("demo")
win.geometry("400x400+200+50")

label1 = tk.Label(win, text="good", bg="blue")
label2 = tk.Label(win, text="nice", bg="red")
label3 = tk.Label(win, text="cool", bg="green")
label1.place(x=10, y=10)  # 绝对布局,窗口的变化对位置没有影响
label2.place(x=50, y=50)
label3.place(x=100, y=100)

label1 = tk.Label(win, text="good", bg="blue")
label2 = tk.Label(win, text="nice", bg="red")
label3 = tk.Label(win, text="cool", bg="green")
label1.pack(fill=tk.Y, side=tk.LEFT)  # 相对布局,窗体改变对控件有影响
label2.pack(fill=tk.X, side=tk.TOP)
label3.pack()

win.mainloop()

 gird布局

import tkinter

win = tkinter.Tk()
win.title("demo")
win.geometry("400x400+200+50")

label1 = tkinter.Label(win, text="good", bg="blue")
label2 = tkinter.Label(win, text="nice", bg="red")
label3 = tkinter.Label(win, text="cool", bg="green")
label4 = tkinter.Label(win, text="handsome", bg="yellow")
label1.grid(row=0, column=0)  # 网格布局
label2.grid(row=0, column=1)
label3.grid(row=1, column=0)
label4.grid(row=1, column=1)

win.mainloop()

菜单

import tkinter as tk
from tkinter import ttk


def showMenu(event):
    menubar.post(event.x_root, event.y_root)


# 创建主窗口
win = tk.Tk()
# 设置标题
win.title("demo")
# 设置大小和位置
win.geometry("800x500+100+50")


menubar = tk.Menu(win)  # 菜单条
win.config(menu=menubar)
menu1 = tk.Menu(menubar, tearoff=False)  # 创建一个菜单选项
for item in ["python", "c", "java", "c++", "c#", "php", "B", "退出"]:
    if item == "退出":
        menu1.add_separator()  # 添加分割线
        menu1.add_command(label=item, command=win.quit)  # 给菜单选项添加内容
    else:
        menu1.add_command(label=item)
menubar.add_cascade(label="语言", menu=menu1)  # 向菜单条上添加菜单选项

win.bind("<Button-3>", showMenu)  # 鼠标右键菜单


# 进入消息循环
win.mainloop()

交互

import tkinter as tk
from tkinter import messagebox, colorchooser, filedialog, simpledialog

root = tk.Tk()
root.withdraw()  # 隐藏主窗口

# 显示不同类型的消息框
messagebox.showinfo("提示", "操作成功")
messagebox.showwarning("警告", "磁盘空间不足")
messagebox.showerror("错误", "文件打开失败")
answer = messagebox.askquestion("确认", "确定要删除吗?")
print("用户选择:", answer)

# 文件选择框
file_path = filedialog.askopenfilename(title="选择文件")
print("选择的文件:", file_path)
save_path = filedialog.asksaveasfilename(title="保存文件")
print("保存路径:", save_path)
dir_path = filedialog.askdirectory(title="选择文件夹")
print("选择的目录:", dir_path)

# 对话框
name = simpledialog.askstring("输入", "请输入您的姓名")
age = simpledialog.askinteger("输入", "请输入年龄")
price = simpledialog.askfloat("输入", "请输入价格")
print(f"用户信息: {name}, {age}岁, 价格{price}")

# 颜色选择器
color = colorchooser.askcolor(title="选择颜色")
print("选择的颜色值:", color)

事件

import tkinter as tk

win = tk.Tk()
win.title("demo")
win.geometry("400x400+200+50")


def mouseEvent(event):
    print(event.type)  # 事件类型
    print(event.num)  # 鼠标按键
    print(event.widget)  # 引起事件的组件
    print(event.x, event.y)  # 鼠标当前位置,相对于窗口
    print(event.x_root, event.y_root)  # 鼠标当前位置,相对于整个屏幕


def keyEvent(event):
    print(event.type)  # 事件类型
    print(event.char)  # 按键字符
    print(event.keycode)  # 按键名
    print(event.widget)  # 引起事件的组件


button = tk.Button(win, text="Mouse Event")
# bind 给控件绑定事件
button.pack()
button.bind("<Button-1>", mouseEvent)  # <Button-1>  鼠标左键点击事件
button.bind("<Button-2>", mouseEvent)  # <Button-2>  鼠标滚轮点击事件
button.bind("<Button-3>", mouseEvent)  # <Button-3>  鼠标右键点击事件
button.bind("<Double-Button-1>", mouseEvent)  # <Double-Button-1>  鼠标双击左键点击事件
button.bind("<Triple-Button-1>", mouseEvent)  # <Triple-Button-1>  鼠标三击左键点击事件


label = tk.Label(win, text="hello world")
label.pack()
label.bind("<B1-Motion>", mouseEvent)  # <B1-Motion>  左键移动
label.bind("<B2-Motion>", mouseEvent)  # <B2-Motion>  中键移动
label.bind("<B3-Motion>", mouseEvent)  # <B3-Motion>  右键移动
label.bind("<ButtonRelease-1>", mouseEvent)  # <ButtonRelease-1> 释放鼠标左键
label.bind("<ButtonRelease-2>", mouseEvent)  # <ButtonRelease-2> 释放鼠标中键
label.bind("<ButtonRelease-3>", mouseEvent)  # <ButtonRelease-3> 释放鼠标右键
label.bind("<Enter>", mouseEvent)  # <Enter>  当鼠标进入控件时触发事件
label.bind("<Leave>", mouseEvent)  # <Leave>  当鼠标离开控件时触发事件


label2 = tk.Label(win, text="hello world")
label2.focus_set()  # 设置焦点
label2.pack()
label2.bind("<Key>", keyEvent)  # <Key>  响应所有的按键(要有焦点)
label2.bind("<Shift_L>", keyEvent)  # <Shift_L>  响应左侧的shift键
label2.bind("<F5>", keyEvent)  # <F5>
label2.bind("<Return>", keyEvent)  # <Return> 回车键
label2.bind("<BackSpace>", keyEvent)  # <BackSpace> 退格键

win.bind("<Control-Alt-A>", keyEvent)
win.bind("<KeyPress-A>", keyEvent)  # 按下A键
win.bind("<Alt-KeyPress-A>", keyEvent)  # <Alt-KeyPress-A> 同时按下alt和A;alt可用ctrl和shift替代
win.bind("<Lock-KeyPress-A>", keyEvent)  # <Lock-KeyPress-A> 大写状态下按A


win.mainloop()

 

posted @ 2023-09-11 11:26  carol2014  阅读(19)  评论(0)    收藏  举报