0

So I'm having an issue, whenever I open the shop window, click the Attack Up 1 button, when the command it's attached to runs, it says that the attackUp1 variable is not defined even though it is set to be the widget. Have a peak at my code:

#opens shop canvas where you buy upgrades
def shop():
    global shop
    root = Tk()
    root.title("Shop")
    shop = Canvas (root, width = 150, height = 400, bg = "blue")
    shop.pack()
    attackUp1 = shop.create_window(77, 50, window = Button(shop, text = "Attack Up 1\n20 coins", font = ("calibri" , 20), command = attackIncreaser1))
    #attackUp2 = shop.create_window(77, 100, window = Button(shop, text = "Attack Up 2\n60 coins", font = ("calibri" , 20), command = shoot))

#runs when someone buys the attackUp1 upgrade and changes their stats or says that they don't have enough coins
def attackIncreaser1():
    global attack
    global attackPower
    global coins
    global shop
    global attackUp1

    if coins < attackUp1Price:
        attackUp1.config(text="Not enough coins")
    elif coins >= attackUp1Price:            
        attackPower = attackPower + 1
        attackUp1.config(text="")
        time.sleep(0.5)
        attackUp1.config(text="Attack Up 1\n20 coins")

1 Answers1

1

This code does not run, which means I'll have to guess what is missing and add it to be able to debug. So my comments may be irrelevant...

I would not recommend creating the root window inside a function.

The variable attackUp1 is created inside the function shop() which makes it local. When the function exits it is garbage collected.

The variable attackUp1 is of type int. That is the nature of canvas objects. If you want to change the button text you'll need to save a reference to the button.

Update As I look at this code again, wondering about why you would create an instance of Tk() inside a function, it seems to me you may be opening a new window. If this is the case you should use Toplevel() instead. It's not a good idea to have more than one root window: Why are multiple instances of Tk discouraged?

As for passing the button reference, this may work:

from tkinter import *

root = Tk()
root.title("Shop")

def shop():
    global attackButton
    shop = Canvas (root, width = 150, height = 100, bg = "blue")
    shop.pack()
    attackButton = Button(shop, text="Attack Up 1\n20 coins",
                          command=attackIncreaser1)
    attackUp1 = shop.create_window(77, 50, window=attackButton)

def attackIncreaser1():
    attackButton.config(text="Not enough coins")

shop()

root.mainloop()
figbeam
  • 7,001
  • 2
  • 12
  • 18