Joi Joi - 6 months ago 19
Python Question

Disable a Tkinter button when variables are at 0

I'm learning python still so the rest of my code may be flawed but my main problem is I cant disable this button when the Wood and Stone variable are at 0. I've tried using a while statement that runs the button.config(state=DISABLED) command when stone > 0 and wood > 0 but that didn't seem to work.

from tkinter import *
from tkinter import tkk

class main:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.CraftPickaxe = Button(frame, text = 'Pickaxe', command = self.craftPick)
self.CraftPickaxe.pack()
###RESOURCES###
self.wood = 1
self.stone = 1
self.pickaxe = 0
def craftPick(self):
self.stone -= 1
self.wood -= 1
self.pickaxe += 1
print(self.stone)
print(self.wood)
print(self.pickaxe)
def loop(self):
while True:
if self.stone < 0 and self.wood < 0:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)



root = Tk()
b = main(root)
root.mainloop()


EDIT:
what I think is happening now is that its not constantly checking the variables to see if it goes below zero and therefore not disabling at all. What I'm thinking may need to happen is a check that runs in the craftPick function.

Answer

I think that your problem is that your variable is 0 and not a negative number.

So when you check if your variable is less than 0 it won't disable it because your variable is not smaller than 0, it is exactly 0.

Try with this better

while True:
    if self.stone < 1 and self.wood < 1:
        self.CraftPickaxe.config(state=DISABLED)
    elif self.stone > 0 and self.wood > 0:
        self.CraftPickaxe.config(state=NORMAL)

Also, you can avoid the loop.

def craftPick(self):
    self.stone -= 1
    self.wood -= 1
    self.pickaxe += 1
    if self.stone < 1 and self.wood < 1:
        self.CraftPickaxe.config(state=DISABLED)
    elif self.stone > 0 and self.wood > 0:
        self.CraftPickaxe.config(state=NORMAL)
Comments