0

I am using tkinter to build a GUI. I have two field, One Entry field for accepting user input and other is submit button. My intention is when the GUI invokes Submit button should be in disabled state, which I achieved by setting state of the button as 'disabled'.

self.submit = ttk.Button(self, text='Submit', state = 'disabled')

So when user starts typing in the entry field, then Submit button state should be changed to 'normal'. Written below function :

def enable_responseButton(self):

        self.user_input.bind("<Key>",self.respond.config(state='normal',command = self.get_response))

And pass the function as command in Entry field as below:

self.input = ttk.Entry(self,state = "normal",command = self.enable_responseButton)

However when I ran my script, GUI opens up and Submit button state is by default enabled even if user did not enter any value. Is there any way I need to wait for user input and until then button will be in disabled state ?

1 Answer 1

3

You can use Variable class objects in sync with entry's text, the button is disabled as long as the entry is empty, and enabled when not in the example below:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk


def toggle_state(*_):
    if entry.var.get():
        button['state'] = 'normal'
    else:
        button['state'] = 'disabled'


if __name__ == '__main__':
    root = tk.Tk()
    entry = tk.Entry(root)
    entry.var = tk.StringVar()
    entry['textvariable'] = entry.var
    entry.var.trace_add('write', toggle_state)
    button = tk.Button(root, text="Button", state='disabled')
    entry.pack()
    button.pack()
    tk.mainloop()
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.