如何在 Tkinter 中创建下拉菜单
Tkinter 中创建下拉菜单有几种方法。
- 使用在 Tkinter 组合框教程中介绍的组合框
- 使用 OptionMenu 控件.
OptionMenu
同组合框控件有些类似,但它是 Tkinter 本身的一个模块,因此你不用跟调用 Combobox
那样需要调用 ttk
。
Tkinter OptionMenu
示例
import tkinter as tk
OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]
app = tk.Tk()
app.geometry('100x200')
variable = tk.StringVar(app)
variable.set(OptionList[0])
opt = tk.OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack()
app.mainloop()
opt = tk.OptionMenu(app, variable, *OptionList)
app
是创建的选项菜单的父级,
variable
是 tk.StringVar
类型的初始文本变量。
*OptionList
是菜单的其他选项。*
是用于数据容器的 unpack,在此处是指 list
。
将值更改时的命令绑定到 OptionMenu
OptionMenu
从选项列表中选择新值时,无法连接对应的命令。你不能像按钮控件那样简单地绑定回调函数。
tk.Button(app, text="Increase", width=30, command=change_label_number)
你需要使用 trace
方法将 observer
回调附加到 OptionMenu
变量。每当变量更改时,它都会触发回调函数。
OptionMenu
回调函数举例
import tkinter as tk
OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]
app = tk.Tk()
app.geometry('100x200')
variable = tk.StringVar(app)
variable.set(OptionList[0])
opt = tk.OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")
labelTest = tk.Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")
def callback(*args):
labelTest.configure(text="The selected item is {}".format(variable.get()))
variable.trace("w", callback)
app.mainloop()
trace
的 observer
有三种模式,
observer 模式 | 解释 |
---|---|
w |
当 variable 被更改或选择时 |
r |
当 variable 被读取时 |
u |
当 variable 被删除时 |
variable.trace("w", callback)
意味着当 variable
被用户更改或选择时它将调用 callback
函数。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn