首页 > 解决方案 > 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 始终可以输入。我究竟做错了什么。如果您仍然不明白发生了什么,请自己运行此代码,您会看到。

非常感谢您的宝贵时间,我期待您的回复。

标签: pythonpython-3.xtkinterradio-buttontkinter-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),仅在选择单选按钮时才会执行。这就是使用单选按钮的意义所在,对吧?

另请注意,当初始代码运行时,选择了整个单选按钮,我认为这可能是因为三态值,以摆脱我知道的两种方法:

  1. 将声明更改self.type为:
self.type = tk.StringVar(value=' ')
  1. 或者,您还可以继续为每个单选按钮添加一个额外的选项tristatevalue=' ',例如:
self.type_entry_one = tk.Radiobutton(text="Garage",..,tristatevalue=' ')

但请确保只执行上述解决方案之一。在此处阅读有关三态值的更多信息。

另请注意,您没有将任何master窗口传递给小部件,只要您只有一个窗口就可以了,在使用多个窗口时,可能会混淆小部件的显示位置。

另请注意,如果这是完整的代码,那么如果没有对 执行任何操作__init__(),则可以删除其定义。


推荐阅读