在 OptionMenu Tkinter 中选择选项时如何将按钮状态从禁用更改为活动

当在选项菜单中选择一个选项时,我试图更改按钮状态,但没有任何变化。谁能告诉我我做错了什么?


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()


牛魔王的故事
浏览 101回答 3
3回答

慕码人2483693

将您的功能更改为: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")另外,您没有调用您的函数,因此要调用它并使效果处于活动状态,请在选项菜单中添加命令参数,例如:options = OptionMenu(app, choose, "op1", "op2",command=lambda _:changeState())使用lambda _:optionmenu 命令需要传递一个 tkinter 变量,以避免这种情况。您还可以为您的函数提供一个参数,但是如果您在其他地方调用您的函数,您将必须传递一个参数,或者您也可以使用类似的参数并point=None摆脱lambda.希望这可以清除错误,如果有任何疑问,请告诉我。

慕的地6264312

您可以在更改时command=changeState添加OptionMenu(...)调用:changeState()optionsdef changeState(pick):    if pick == "op2":        button['state'] = ACTIVE        button.config(text = "ACTIVE")    else:        button['state'] = DISABLED        button.config(text = "Disabled")...options = OptionMenu(app, choose, "op1", "op2", command=changeState)

至尊宝的传说

知道了!编辑:我稍微改变了第9行,删除了button.active并替换为NORMAL,这有效。from tkinter import *def setLabel():    changed.set("Active")    def changeState(*args):    pick = choose.get()    if (pick == "op2"):        button['state'] = NORMAL        button.config(text = "ACTIVE")    else:        button['state'] = DISABLED        button.config(text = "Disabled")app = Tk()app.resizable(40,40)choose = StringVar()choose.set("op1")options = OptionMenu(app, choose, "op1", "op2")choose.trace("w", changeState)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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python