标签 - Label
- 组件[“属性”]:获取组件属性值
- 组件[“属性”] = 新值:修改组件属性值
- text:标签内文本
- width:标签空间的宽度
- anchor:标签内文本对齐方式,可选W(左对齐)、CENTER(居中对齐)、E(右对齐),默认CENTER
from tkinter import *
window = Tk()
window.geometry('400x200')
def enter_handle(): # 单击事件
print(label["text"]) # 获取值
label["text"] = "嘻嘻嘻" # 修改值
label = Label(window, text="哈哈哈")
label.pack()
button = Button(window, text='确定', cursor="hand2", command=enter_handle)
button.pack()
window.mainloop()
单行文本框 - Entry
- textvariable:单行文本框变量,String类型,可以使用变量的set和get可以获取或设置值
- show:单行文本框内文字显示方式,如密码可以将值设为
show="*"
- state:文本框输入状态,默认NORMAL表示可以输入,DISABLED表示无法输入
from tkinter import *
window = Tk()
window.geometry('400x200')
def enter_handle(): # 打印事件
print("账号:", username.get()) # 获取单行文本框内容
print("密码:", password.get())
def clear_handle(): # 清空事件
username.set("") # 设置单行文本框内容
password.set("")
"""账号框架"""
username_frame = Frame(window)
Label(username_frame, text="账号:").pack(side=LEFT) # 组件按照自左向右方向排列
username = StringVar() # 与单行文本框绑定的变量
Entry(username_frame, textvariable=username).pack(side=LEFT)
username_frame.pack(pady=5) # 组件之间的水平间距
"""密码框架"""
password_frame = Frame(window)
Label(password_frame, text="密码:").pack(side=LEFT)
password = StringVar()
Entry(password_frame, textvariable=password, show="*").pack(side=LEFT)
password_frame.pack(pady=5)
"""按钮框架"""
button_frame = Frame(window)
Button(button_frame, text='确定', cursor="hand2", width=5, command=enter_handle).pack(side=LEFT, padx=10)
Button(button_frame, text='清空', cursor="hand2", width=5, command=clear_handle).pack(side=LEFT, padx=10)
button_frame.pack()
window.mainloop()
多行文本框 - Text
- width、height:文本框的宽度和高度
- insert(index, text):在指定位置index插入text
- index可以使用“line.column”的形式, line从1开始,column从0开始
"1.0"
代表第一行第一列(文本开始),"end"
代表文本最后,"insert"
代表广标插入处
- delete(start, end):删除从start到end的文本
- get(start,end):获取从start到end的文本
from tkinter import *
window = Tk()
window.geometry('400x200')
def enter_handle():
print(my_text.get("1.0", "end")) # 获取值
my_text = Text(window, height=5, width=20)
my_text.insert("1.0", "哈哈哈") # 从开头插入值
my_text.insert("end", "嘻嘻嘻") # 从最后插入值
my_text.pack()
Button(window, text='确定', cursor="hand2", command=enter_handle).pack()
Button(window, text='清空', cursor="hand2", command=lambda: my_text.delete("1.0", "end")).pack() # 清空值
Button(window, text='插入', cursor="hand2", command=lambda: my_text.insert("insert", "666")).pack() # 在光标处插入值
window.mainloop()
数值输入框 - Spinbox
- from_:起始值(最小)
- to:结束值(最大)
- increment:单击调节箭头时递增或者递减的精度(步长)
- textvariable:单行文本框变量,Int类型,可以使用变量的set和get可以获取或设置值
- justify:输入框内文字对齐方式(CENTER、LEFT、RIGHT)
from tkinter import *
window = Tk()
window.geometry('400x200')
def enter_handle(): # 单击调节箭头时触发
print(spinbox_var.get()) # 获取值
spinbox_var = IntVar()
Spinbox(window,from_=0,to=10,increment=1,textvariable=spinbox_var,
justify=CENTER,command=enter_handle).pack()
spinbox_var.set(6) # 设置值
mainloop()
单选框 - Radiobutton
- text:复选框显示的文本
- variable:单选框变量,多个单选框使用同一个变量
- 变量类型任意(下面我使用的是文本索引作为变量的值,也就是Int类型)
- 可以使用变量的set和get获取或设置值
- value:单选框变量对应的值
- command:绑定单击事件,单击单选框时触发
from tkinter import *
window = Tk()
window.geometry('400x200')
def radio_handle(): # 单击任意单元框时触发
print("哈哈哈哈")
def enter_handle(): # 单击事件
print(radio_var.get()) # 获取单元框的值
print(radio_texts[radio_var.get()]) # 获取单元框的文本
radio_texts = ["Java", "Python", "C++", "PHP"] # 单选框文本
radio_var = IntVar() # 单选框变量
for index, text in enumerate(radio_texts):
Radiobutton(window, text=text, variable=radio_var, value=index, command=radio_handle).pack()
radio_var.set(2) # 设置第三个单元框选中
Button(window, text='确定', cursor="hand2", command=enter_handle).pack()
window.mainloop()
复选框 - Checkbutton
- text:复选框显示的文本
- variable:复选框变量,各个复选框变量独立
- 通常使用Boolean类型,True代表选中,False代表未选中
- 可以使用变量的set和get可以获取或设置值
- command:绑定单击事件,单击复选框时触发
from tkinter import *
window = Tk()
window.geometry('400x200')
def check_handle(): # 单击任意复选框时触发
print("哈哈哈哈")
def enter_handle(): # 单击事件
check_selects = []
for index, var in enumerate(check_vars):
if var.get(): # 获取复选框状态,True代表选中,False代表未选中
check_selects.append(check_texts[index])
print(check_selects) # 打印出所有的选择项
check_texts = ["唱歌", "跳舞", "绘画", "编程"] # 复选框文本
check_vars = [BooleanVar() for i in check_texts] # 复选框变量
for index, text in enumerate(check_texts):
Checkbutton(window, text=text, variable=check_vars[index], command=check_handle).pack()
check_vars[1].set(True) # 设置第二个复选框选中
check_vars[3].set(True) # 设置第四个复选框选中
Button(window, text='确定', cursor="hand2", command=enter_handle).pack()
window.mainloop()
下拉框 - Combobox
- values:下拉框选项
- textvariable:下拉框变量,String类型,可以使用变量的set和get可以获取或设置值
- bind(“<<ComboboxSelected>>”, callback):绑定下拉框选择事件
from tkinter import *
from tkinter.ttk import Combobox
window = Tk()
window.geometry('400x200')
def enter_handle(): # 单击事件
print(combobox_var.get()) # 获取值
def combobox_selected(event): # 下拉框选择时触发
print(combobox_var.get()) # 获取值
values = ["唱歌", "跳舞", "绘画", "编程"]
combobox_var = StringVar()
combobox = Combobox(window, values=values, width=10, textvariable=combobox_var)
combobox_var.set(values[2]) # 设置值为第三个
combobox.bind("<<ComboboxSelected>>", combobox_selected) # 绑定下拉框选择事件
combobox.pack()
Button(window, text='确定', cursor="hand2", command=enter_handle).pack()
window.mainloop()
消息提示框 - messagebox
导入:from tkinter import messagebox
from tkinter import *
from tkinter import messagebox
window = Tk()
window.geometry('400x200')
def enter_handle():
messagebox.showinfo("标题","我是消息提示框")
messagebox.showwarning("标题","我是警告提示框")
messagebox.showerror("标题","我是错误提示框")
Button(window, text='确定', cursor="hand2", command=enter_handle).pack()
window.mainloop()
文件对话框 - filedialog
导入:from tkinter import filedialog
上述方法的常用参数值如下所示:
- title:指定文件对话框的标题
- filetypes: 指定筛选文件类型的下拉菜单选项,该选项值是由元祖构成的列表,其中每个二元祖由两部分组成 (类型名,后缀)
- initialfile:保存文件时的默认文件名,可修改
- initialdir:指定打开/保存文件的默认路径,默认路径是最近一次打开的文件夹路径
- defaultextension:指定文件的后缀名,当保存文件时自动添加文件名,如果自动添加了文件的后缀名,则该选项值不会生效
import os
from tkinter import *
from tkinter import filedialog
window = Tk()
window.geometry('400x200')
def handle1():
file = filedialog.askdirectory() # 选择文件夹
if file is not None:
print(file) # 打印文件夹路径
def handle2():
file = filedialog.askopenfilename() # 选择文件
if len(file) > 0:
print(file) # 打印文件路径
def handle3():
file = filedialog.asksaveasfilename(initialfile="默认文件名.xlsx",
initialdir=os.getcwd(), # 默认保存到当前工作文件夹
filetypes=[("XLSX", "*.xlsx")])
if len(file) > 0:
print(file) # 返回保存的文件路径,但不具备保存文件的能力
else:
print("未选择")
Button(window, text='选择文件夹', cursor="hand2", command=handle1).pack()
Button(window, text='选择文件', cursor="hand2", command=handle2).pack()
Button(window, text='保存文件', cursor="hand2", command=handle3).pack()
window.mainloop()