简体   繁体   English

如果满足某些条件,如何配置Tkinter小部件?

[英]How to configure Tkinter widgets if certain conditions are met?

Normally, this isn't hard. 通常,这并不难。 I can usually do it without much trouble. 我通常可以轻松完成此操作。 For example: 例如:

b = Button(main, text="Button", command=function)
x = 3
def function():
    x -=1
if x == 0:
    b.configure(state=DISABLED)

This would disable my button after pushing it three times. 按下三下后,这将禁用我的按钮。 However, my issue is slightly more complicated. 但是,我的问题稍微复杂一些。 I want a button that can switch back and forth based on a variable, not just go from one to the other one time. 我想要一个可以基于变量来回切换的按钮,而不仅仅是一次又一次地切换。 In my real thing, all variables are IntVar or StringVar . 实际上,所有变量都是IntVarStringVar

addB = Button(main, text="Add", command=add)
subtractB = Button(main, text="Subtract", command=subtract)

x = IntVar()
x.set(0)

def add():
    x.set(x.get() + 1)

def subtract():
    x.set(x.get() - 5)

At this point, I'm looking for something that'll disable the subtract button ( subtractB.configure(state=DISABLED) ) unless x is at least five. 此时,除非x至少为5,否则我正在寻找可以禁用减法按钮的东西( subtractB.configure(state=DISABLED) )。 If x is more than five before the button is pressed and then x becomes less than five again, the button should disable itself again. 如果在按下按钮之前x大于5,然后x再次小于5,则按钮应再次禁用自身。 How is this done? 怎么做?

You can trace an IntVar , which means you call a function every time the variable is changed. 您可以trace IntVar ,这意味着每次更改变量时都调用一个函数。 This way you can check the value of x every time it is changed, and set the state of the button accordingly: 这样,您可以在每次更改x时检查x的值,并相应地设置按钮的状态:

def add():
    x.set(x.get() + 1)

def subtract():
    x.set(x.get() - 5)

def trace_var(*args):
    if x.get() < 5:
        subtractB.configure(state=DISABLED)
    else:
        subtractB.configure(state=NORMAL)


main = Tk()

addB = Button(main, text="Add", command=add)
addB.pack()
subtractB = Button(main, text="Subtract", command=subtract)
subtractB.pack()

x = IntVar()
x.trace('w', trace_var)
x.set(0)
Label(main, textvariable=x).pack()

main.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM