我试图创建一个窗口,其中包含一个基于fileselection对话框填充的optionmenu。我可以使选项菜单包含基于先前选择的文件的所有选项。但是,无论用户选择了哪个选项,变量都包含从所选文件中读取的最后一个选项。在
如果有人能解释一下为什么会这样。因此,我在下面列出了一个最小的例子:
from Tkinter import *
Tk()
class App():
chunks = ['A','B','C'] # These are read from a file in the actual program
testVariable = StringVar()
def __init__(self,master):
def initSummary():
self.dataButton["menu"].delete(0, 'end')
for i in self.chunks:
print i # To demonstrate what's in there
self.dataButton["menu"].add_command(label=i, command = lambda: self.testVariable.set(i))
top = self.top = Toplevel()
top.protocol("WM_DELETE_WINDOW", lambda: close(self))
self.sumButton = Button(top, text="Test", width=25, command=lambda: initSummary())
self.sumButton.grid(row=0, column=0, sticky=W)
self.dataButton = OptionMenu(top, self.testVariable, "Stuff")
self.dataButton.grid(row=0, column=1, sticky=W)
# Call the main app
root = Tk()
app = App(root)
root.mainloop()
此代码将在option菜单上显示C
,而不管用户选择了什么,而代码中的print
将生成预期的A
、B
和{print
也显示了3次C
,我会理解的,但是打印的内容和GUI中显示的内容不匹配让我很困惑。在
我已经修复了for循环中lambda的问题(感谢@j_4321),方法是添加一个中间函数,如下面的代码所示。在
如果这不是解决此问题的“正确”方式,请发表意见。在
相关问题 更多 >
编程相关推荐