python - 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)。
解决方案
问题出在这一行
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
.
推荐阅读
- webpack - Material UI:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:null
- java - 我的 String.split() 函数运行不正常,我不知道为什么?
- c++ - 在qt上找不到libssh的功能
- python - Ubuntu 卸载所有 Python 和 Pip
- java - 如何打开文件.so?
- database - 在 PostgreSQL 中的某些偏移量中重复某些行
- c++ - String is ambiguous
- javascript - 有人可以帮助我使用这种从某些值中拆分数组的算法吗?
- javascript - Angular - 从可共享的 URL 加载应用程序
- c++ - C++ 中的左移 - 意外结果