修复我的代码以使用禁用按钮

时间:2019-05-12 07:42:12

标签: python python-3.x tkinter

如何通过将所有购买按钮附加到if语句(例如第一个购买按钮)来禁用所有购买按钮

if counter.get()>15:
 state="disabled
else:
 state="enabled"

我尝试了20到50种不同的方法,甚至将我的整个代码更改为网格样式。我只想要我拥有的代码以及一种禁用按钮直到满足条件的简单方法。很难解决这个问题。

import tkinter

root = tkinter.Tk()
root.geometry("480x320")
root.title("Button Clicker")

counter = tkinter.IntVar()
Ant = tkinter.IntVar()
autoclicker = 0

def onClick(event=None):
    counter.set(counter.get() + 1)

def buyAnt(event=None):
    if counter.get()-10>=0:
        counter.set(counter.get() -10) ,Ant.set(Ant.get() + 1)

def buyCat(event=None):
    if counter.get()-50>=0:
        counter.set(counter.get() -50)

def buyDog(event=None):
    if counter.get()-100>=0:
        counter.set(counter.get() -100)

def buyVillager(event=None):
    if counter.get()-200>=0:
        counter.set(counter.get() -200)

def autoclick(event=None):
    counter.set(counter.get()+1)
    root.after(1000, autoclick )

def buyAutoClicker(event=None):
    if counter.get()-15>=0:
        counter.set(counter.get() -15), autoclicker + 1, 
            root.after(1000, autoclick)


tkinter.Label(root, textvariable=counter).pack()
tkinter.Label(root, textvariable=Ant).pack()
tkinter.Button(root, text="Click", command=onClick, fg="dark green", 
    bg = "white").pack()

btn2 = tkinter.Button(root, text="Buy AutoClicker", 
    command=buyAutoClicker, fg="dark green", bg = "white").pack()

tkinter.Button(root, text="Buy Cat", command=buyCat, fg="dark green", 
    bg = "white").pack()

tkinter.Button(root, text="Buy Dog", command=buyDog, fg="dark green", 
    bg = "white").pack()

tkinter.Button(root, text="Buy Villager", command=buyVillager, 
    fg="dark green", bg = "white").pack()


root.mainloop()

我希望点击(正常)购买自动点击程序(灰色,直到柜台> 15)

1 个答案:

答案 0 :(得分:1)

通过configure方法,您可以更改窗口小部件的选项,并且可用参数取决于您正在配置的窗口小部件。通过调用state参数并将其值设置为“ normal”或“ disabled”来更改窗口小部件的状态:wdiget.configure(state = 'disabled')

代码的第一个问题是您删除了要更改其状态的对按钮小部件的唯一引用。这可以通过将.pack()方法拆分为新行来解决:

btn2 = tkinter.Button(root, text="Buy AutoClicker", 
    command=buyAutoClicker, fg="dark green", bg = "white", state = 'disabled') # also you might consider setting the initial state of the button to 'disable'
btn2.pack() # note here

关于检查计数器的值和更新按钮状态,可以通过将回调函数附加到tkinters IntVar()并在其更改时捕获它来完成:

...

def onClick(event=None):
    counter.set(counter.get() + 1)

def callback(name, index, op):
    print("called")
    if counter.get() < 15:
        btn2.configure(state = 'disabled')
    else:
        btn2.configure(state = 'normal')

counter.trace("w", callback)

tkinter.Label(root, textvariable=counter).pack()
tkinter.Label(root, textvariable=Ant).pack()

...

这将使您的按钮“ Buy AutoClicker”处于禁用状态,而计数器小于15。如果要同时禁用多个按钮,则需要创建一个列表。