rm24
rm24

Reputation: 27

Using Tkinter to disable entry with specified input

I would like to use Tkinter to be able to disable one entry if 'no' is selected from a drop down menu.

from tkinter import *

def disableEntry(entry):
    entry.config(state='disable')

def allowEntry(entry):
    entry.config(state='normal')


def main():
    print("test")

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text = "Label 1").grid(row=0, column=0, padx=30, pady=(20,5))
L2 = Label(root, text = "Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root,bd =3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root,var,"yes","no")
D1.grid(row=1,column=1)

if var.get() == 'no':
    disableEntry(E1)
elif var.get() == 'yes':
    allowEntry(E1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()

the above code is a simple example of what i have tried. I have created two functions called 'disableEntry' and 'allowEntry' which should change the state of the entry box but they don't appear to do anything when i change the input of the drop down menu.

i dont know if i am approaching this the wrong way or if there is a standardized way to do this.

any help would be appreciated.

Upvotes: 0

Views: 865

Answers (1)

Axe319
Axe319

Reputation: 4365

You need a way to check the state of the selection after it is changed. That can be achieved with adding a callback command to the OptionMenu widget.

You were checking the correct variable, but the point you were checking it at was before the screen window had even displayed.

from tkinter import Label, StringVar, OptionMenu, Entry, Tk, Button

# change the state of the Entry widget
def change_state(state='normal'):
    E1.config(state=state)

def main():
    print("test")

# callback function triggered by selecting from OptionMenu widget
def callback(*args):
    if var.get() == 'no':
        change_state(state='disable')
    elif var.get() == 'yes':
        change_state(state='normal')

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text="Label 1").grid(row=0, column=0, padx=30, pady=(20, 5))
L2 = Label(root, text="Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root, bd=3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root, var, "yes", "no", command=callback)
D1.grid(row=1, column=1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()

Upvotes: 1

Related Questions