pythonpython-3.xtkintertkinter.optionmenu

How to change a buttons state from disabled to active when an option is selected in an OptionMenu Tkinter


I'm trying to change the button state when an option is selected in the option menu, but nothing is changing. Can anyone tell me what I'm doing wrong?

from tkinter import *

def setLabel():
    changed.set("Active")
    
def changeState():
    pick = choose.get()
    if (pick == "op2"):
        button['state'] = button.ACTIVE
        button.config(text = "ACTIVE")
    else:
        button['state'] = app.DISABLED
        button.config(text = "Disabled")

app = Tk()
app.resizable(40,40)

choose = StringVar()
choose.set("op1")
options = OptionMenu(app, choose, "op1", "op2")
options.pack()


button = Button(app, text = "Disabled", state = DISABLED, command = setLabel)
button.pack()

changed = StringVar()
label = Label(app, textvariable = changed, font = ("helvetica", 10))
label.pack()

app.mainloop()

Solution

  • Change your function to this:

    def changeState():
        pick = choose.get()
        if (pick == "op2"):
            button['state'] = ACTIVE #means active state
            button.config(text = "ACTIVE")
        else:
            button['state'] = DISABLED #means disabled state
            button.config(text = "Disabled")
    

    Also your not calling your function, so to call it and make the effect active, add a command argument onto your optionmenu, like:

    options = OptionMenu(app, choose, "op1", "op2",command=lambda _:changeState())
    

    Using lambda _: because optionmenu command expect a tkinter variable to be passed on, so as to avoid that. You could also have a parameter for your function, but if your calling your function somewhere else, your gonna have to pass in a argument or your could also use parameter like point=None and get rid of the lambda.

    Hope this cleared the errors, do let me know if any doubts.

    Cheers