首页 > 解决方案 > Tkinter 通过命令 lambda 传递 StringVar.get 给出初始值

问题描述

好的,所以我正在尝试使用 Tkinter 制作菜单系统,并尝试将下拉菜单的字符串值保存到类变量中。我有处理该部分的代码,但问题在于将该字符串值传递给我编写的函数。我知道问题不是我的功能,因为我在下面的示例中使用了打印功能。

import tkinter as tk
from enum import Enum

class CustomEnum(Enum):
    Option1 = 'Option1'
    Option2 = 'Option2'


class window():
    def __init__(self, root):
        self.value = CustomEnum.Option1

        test = tk.StringVar()
        test.set(self.value.value)

        tk.OptionMenu(root, test, *[e.value for e in CustomEnum], command = lambda
            content = test.get() : print(content)).pack()

        tk.Button(root, text="Save",
            command =  lambda content = test.get() : print(content)).pack()


root = tk.Tk()
test = window(root)
root.mainloop()

如果您运行此代码,它会不断打印“选项 1”,无论您选择了什么选项或者添加或删除元素(除了删除选项 1)。

标签: pythontkinterlambdaoptionmenu

解决方案


问题出在这一行

tk.Button(root, text="Save",
    command = lambda content = test.get() : print(content)).pack()

您正在分配那一刻 ( )content的值,并且它仍然保持不变。test.get()Option1

由于您想要 的当前值test.get(),因此您必须这样做

command = lambda: print(test.get())).pack()

另外,我相信您拼写错误customEnum而不是CustomEnum.


推荐阅读