OptionMenu 组件
OptionMenu(选项菜单)事实上是下拉菜单的改版,它的发明弥补了 Listbox 组件无法实现下拉列表框的遗憾。创建一个选择菜单非常简单,只需要它一个 Tkinter 变量(用于记录用户选择了什么)以及若干选项即可:
python
import tkinter as tk
root = tk.Tk()
root.geometry('500x300')
variable = tk.StringVar()
variable.set("选项一")
w = tk.OptionMenu(root, variable, "选项一", "选项二", "选项三")
w.pack()
root.mainloop()
要获得用户选择的内容,使用Tkinter变量的get()方法即可:
python
import tkinter as tk
root = tk.Tk()
root.geometry('500x300')
variable = tk.StringVar()
variable.set("选项一")
w = tk.OptionMenu(root, variable, "选项一", "选项二", "选项三")
w.pack()
def callback():
print(variable.get())
tk.Button(root, text="点我", command=callback).pack()
root.mainloop()
最后演示如何将很多选项快速添加到选项菜单中:
python
import tkinter as tk
options = [
'新建',
'删除',
'撤销',
'反撤销'
]
root = tk.Tk()
root.geometry('500x300')
variable = tk.StringVar()
variable.set("选项一")
w = tk.OptionMenu(root, variable, *options)
w.pack()
def callback():
print(variable.get())
tk.Button(root, text="点我", command=callback).pack()
root.mainloop()