簡體   English   中英

tkinter 選項菜單不會為通過.add_command() 創建的選定選項返回正確的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM