python - Tkinter 基于单选按钮更改条目状态
问题描述
我有四个单选按钮。这四个按钮下方是一个Entry
小部件。我试图让这个Entry
小部件只有在选择最后一个单选按钮时才可以输入。它gui
在一个类中,如下面的代码所示:
class Gui:
def __init__(self):
pass
def draw(self):
global root
if not root:
root = tk.Tk()
root.geometry('280x350')
self.type = tk.StringVar()
self.type_label = tk.Label(text="Game Mode")
self.name_entry = tk.Entry()
self.name_entry.configure(state="disabled")
self.name_entry.update()
self.type_entry_one = tk.Radiobutton(text="Garage", value="garage", variable=self.type, command=self.disable_entry(self.name_entry))
self.type_entry_two = tk.Radiobutton(text="Festival", value="festival", variable=self.type, command=self.disable_entry(self.name_entry))
self.type_entry_three = tk.Radiobutton(text="Studio", value="studio", variable=self.type, command=self.disable_entry(self.name_entry))
self.type_entry_four = tk.Radiobutton(text="Rockslam", value="rockslam", variable=self.type, command=self.enable_entry(self.name_entry))
self.type_label.pack()
self.type_entry_one.pack()
self.type_entry_two.pack()
self.type_entry_three.pack()
self.type_entry_four.pack()
self.name_entry.pack()
root.mainloop()
def enable_entry(self, entry):
entry.configure(state="normal")
entry.update()
def disable_entry(self, entry):
entry.configure(state="disabled")
entry.update()
if __name__ == '__main__':
root = None
gui = Gui()
gui.draw()
但是,self.name_entry 始终可以输入。我究竟做错了什么。如果您仍然不明白发生了什么,请自己运行此代码,您会看到。
非常感谢您的宝贵时间,我期待您的回复。
解决方案
唯一的问题,我明白了,你在这里面临的是因为你没有将值“正确”传递给函数,当你使用时(..)
,你调用函数,所以要摆脱那个 use lambda
,比如:
self.type_entry_one = tk.Radiobutton(text="Garage", value="garage", variable=self.type, command=lambda: self.disable_entry(self.name_entry))
self.type_entry_two = tk.Radiobutton(text="Festival", value="festival", variable=self.type, command=lambda:self.disable_entry(self.name_entry))
self.type_entry_three = tk.Radiobutton(text="Studio", value="studio", variable=self.type, command=lambda:self.disable_entry(self.name_entry))
self.type_entry_four = tk.Radiobutton(text="Rockslam", value="rockslam", variable=self.type, command=lambda:self.enable_entry(self.name_entry))
使用 时command=lambda:func(arg)
,仅在选择单选按钮时才会执行。这就是使用单选按钮的意义所在,对吧?
另请注意,当初始代码运行时,选择了整个单选按钮,我认为这可能是因为三态值,以摆脱我知道的两种方法:
- 将声明更改
self.type
为:
self.type = tk.StringVar(value=' ')
- 或者,您还可以继续为每个单选按钮添加一个额外的选项
tristatevalue=' '
,例如:
self.type_entry_one = tk.Radiobutton(text="Garage",..,tristatevalue=' ')
但请确保只执行上述解决方案之一。在此处阅读有关三态值的更多信息。
另请注意,您没有将任何master
窗口传递给小部件,只要您只有一个窗口就可以了,在使用多个窗口时,可能会混淆小部件的显示位置。
另请注意,如果这是完整的代码,那么如果没有对 执行任何操作__init__()
,则可以删除其定义。
推荐阅读
- numbers - 查找给定自然数中是否有奇数的最快方法是什么
- python - 如何修复这个通过参数化函数列表迭代的“for”循环?
- r - 如何在R中获得摘要基分类
- powershell - 从 CSV 禁用/启用 AD 用户帐户
- mercurial - Tortoise 上的 Mercurial HG 卡住 - 等待锁定工作目录
- tsql - 如何在 SSIS 表达式的列中删除 2 个特殊字符之间的多个字符
- javascript - 如何根据新旧数据过滤数据
- laravel - 如何为 laravel 8 工厂设置参数?
- nginx - 我想从移动应用程序访问 Zammand(在 nginx 上运行),但我得到标准的“欢迎使用 nginx”?
- javascript - 从 index.ts 导入返回 undefined