如何在 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