尝试在更新所有条目后更改按钮的状态

时间:2016-10-18 08:14:50

标签: python tkinter

尝试在编写条目后了解如何启用按钮状态。我想要一个新窗口Toplevel。其中,有三个条目小部件。填充值后,应启用RUN按钮。我知道我必须使用trace方法将观察者回调附加到变量。这是我到目前为止所做的。

class appl:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame( self.master, width=800, height=700 )
        self.var = tk.IntVar( )
        self.func1 = tk.Radiobutton( self.frame, text='fun1', value=1, variable=self.var,command=self.new_window )
        self.func1.pack( )
        self.frame.pack( )
    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.intvar1 = tk.IntVar()
        self.intvar2 = tk.IntVar()
        self.intvar3 = tk.IntVar()
        self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check ).grid(row=3, column=1 )
        self.intvar1.trace( 'w', self.validate_check )
        self.intvar2.trace( 'w', self.validate_check )
        self.intvar3.trace( 'w', self.validate_check )
        self.X = tk.Entry( self.newWindow,textvariable=self.intvar1 )
        self.Y = tk.Entry( self.newWindow, textvariable=self.intvar2)
        self.Z = tk.Entry( self.newWindow, textvariable=self.intvar3)
        self.X.grid( row=0, column=1 )
        self.Y.grid( row=1, column=1 )
        self.Z.grid( row=2, column=1 )
        tk.Label( self.newWindow, text=" X" ).grid( row=0 )
        tk.Label( self.newWindow, text=" Y" ).grid( row=1 )
        tk.Label( self.newWindow, text=" Z" ).grid( row=2 )
    def validate_check(self, *args):
        x = self.intvar1.get()
        y = self.intvar2.get()
        z = self.intvar3.get()
        if x and y and z:
            self.ent.config(state=NORMAL)
        else:
            self.ent.config(state=DISABLED)
def main():
    root = tk.Tk()
    app = appl(root)
    root.mainloop()
if __name__ == '__main__':
    main() 

1 个答案:

答案 0 :(得分:3)

您的代码几乎正常工作,除了:

self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check ).grid(row=3, column=1 )

应该是:

self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check )
self.ent.grid(row=3, column=1 )

此外,当您在输入框中输入0-9以外的内容时,validate_check(...)将引发异常,因为条目文本无法转换为整数值。尝试将validate_check(...)更改为:

def validate_check(self, *args):
    try:
        x = self.intvar1.get()
        y = self.intvar2.get()
        z = self.intvar3.get()
        # all three entries are valid integers, enable the button
        self.ent.config(state=tk.NORMAL)
    except:
        # something wrong on the entries, disable the button
        self.ent.config(state=tk.DISABLED)