![](/img/trans.png)
[英]tkinter option menu doesn't execute callback function for option created via .add_command(label='New Item')
[英]tkinter option menu doesn't return the correct value for selected options created via .add_command()
我的第一次 tkinter 體驗進行得相當順利,但現在我被難住了。
我得到了幫助,並在研究時從另一個線程中找到了一些修改過的測試代碼。 但是,我無法讓代碼在我的實際項目中工作。
我試圖弄清楚為什么用for x in ['d', 'e', 'f']: menu['menu'].add_command(label=x, command=lambda: callback(x))
替換menu['menu'].add_command(label='New Item')
。 for x in ['d', 'e', 'f']: menu['menu'].add_command(label=x, command=lambda: callback(x))
中斷。
The last new entry added (f in this case) is always returned when one of the other newly created entries d or e is selected, while the initial entries a, b, & c continue to work as expected.
工作示例:
import tkinter as tk
def callback(selection):
print(selection)
options.set(selection)
root = tk.Tk()
options = tk.StringVar()
menu = tk.OptionMenu(root, options, 'a', 'b', 'c', command=callback)
menu.pack()
menu['menu'].add_command(label='New Item', command=lambda: callback('New Item'))
options.set('a')
root.mainloop()
破例:
import tkinter as tk
def callback(selection):
print(selection)
options.set(selection)
root = tk.Tk()
options = tk.StringVar()
menu = tk.OptionMenu(root, options, 'a', 'b', 'c', command=callback)
menu.pack()
for x in ['d', 'e', 'f']:
menu['menu'].add_command(label=x, command=lambda: callback(x))
options.set('a')
root.mainloop()
正確的。 這是 Python 中的一個可愛的小陷阱。 正如你所擁有的,你的回調 function 中的x
指的是循環變量,當循環結束時, x
總是'f'。 要完成這項工作,您需要“捕獲”變量的值。 這就是@TheLizzard 向您展示的內容
lambda x=x: callback(x)
lambda 中的x
現在指的是參數,並且在創建 lambda 時會捕獲參數的默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.