Tkinter选项菜单小部件添加命令lambda未生成预期的命令

2024-06-07 05:39:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个窗口,其中包含一个基于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将生成预期的AB和{}。如果print也显示了3次C,我会理解的,但是打印的内容和GUI中显示的内容不匹配让我很困惑。在


Tags: 文件lambda用户infromselftop选项
1条回答
网友
1楼 · 发布于 2024-06-07 05:39:40

我已经修复了for循环中lambda的问题(感谢@j_4321),方法是添加一个中间函数,如下面的代码所示。在

from Tkinter import *

class App():

    chunks = ['A','B','C']

    def __init__(self,master):

        self.testVariable = StringVar()

        def refresh():
            # Prints what's in the variable
            print self.testVariable.get()

        def testFunc(x):
            return lambda: self.testVariable.set(x)

        def initSummary():
            self.dataButton["menu"].delete(0, 'end')
            for i in self.chunks:
                self.dataButton["menu"].add_command(label=i, command = testFunc(i))

        top = self.top = Toplevel()
        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)
        self.testButton = Button(top, text="Variable", width=25, command = lambda: refresh())
        self.testButton.grid(row=1, column=0, sticky=W)

# Call the main app
root = Tk()
app = App(root)
root.mainloop()

如果这不是解决此问题的“正确”方式,请发表意见。在

相关问题 更多 >