0

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

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

3 回答 3

0

将您的功能更改为:

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 变量,以避免这种情况。你也可以为你的函数设置一个参数,但是如果你在其他地方调用你的函数,你将不得不传入一个参数,或者你也可以使用参数 likepoint=None并摆脱lambda.

希望这清除了错误,如果有任何疑问,请告诉我。

干杯

于 2020-09-25T10:49:29.513 回答
0

知道了!

编辑:我稍微更改了第 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()
于 2020-09-25T11:08:38.167 回答
0

每当更改时command=changeState,您都可以添加OptionMenu(...)调用:changeState()options

def 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)
于 2020-09-25T11:35:48.313 回答