Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tkinter传递StringVar.get through命令lambda给出初始值_Python_Tkinter_Lambda_Optionmenu - Fatal编程技术网

Python Tkinter传递StringVar.get through命令lambda给出初始值

Python Tkinter传递StringVar.get through命令lambda给出初始值,python,tkinter,lambda,optionmenu,Python,Tkinter,Lambda,Optionmenu,好的,我尝试使用Tkinter创建一个菜单系统,并尝试将下拉菜单的字符串值保存到一个类变量中。我有代码来处理这一部分,但问题是如何将字符串值添加到我编写的函数中。我知道问题不在于我的函数,因为我在下面的示例中使用了print函数 import tkinter as tk from enum import Enum class CustomEnum(Enum): Option1 = 'Option1' Option2 = 'Option2' class window():

好的,我尝试使用Tkinter创建一个菜单系统,并尝试将下拉菜单的字符串值保存到一个类变量中。我有代码来处理这一部分,但问题是如何将字符串值添加到我编写的函数中。我知道问题不在于我的函数,因为我在下面的示例中使用了print函数

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”。

问题在于这一行

tk.按钮(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

谢谢。这么简单的答案,到那时,我仍然在学习tkinter