Kakarico
Kakarico

Reputation: 33

Label doesn't update the variable

I am new to Python, but I learned some things, and now I am trying to make a simple game. I want the label to show the energy, but it doesn't update when the energy changes. My code:

def start_def():
    global main
    main.destroy()  

    def run():
        global energy
        energy = energy - 25
        print(energy)

    game = Tk()
    game.title("Anne: O Jogo")
    game.geometry("800x600")
    game.resizable(0,0)

    global energy
    energy = int(100)

    global img
    img = ImageTk.PhotoImage(Image.open("anne.jpg"))
    panel = Label(game, image=img)
    panel.pack(side="left", pady=5, padx=5)
    panel.place(x=15, y=15)

    Label(game, text="Anne", font=("Verdana", 25, "bold")).place(x=220, y=20)
    Label(game, text="Energia: ", font=("Verdana", 15, "bold")).place(x=220, y=70)
    Label(game, text=energy, font=("Verdana", 15, "bold")).place(x=320, y=71)

    b = Button(game, text="Correr", command=run).pack()

`

This is a part from my entire code, if you guys need the rest of it, just ask. Thanks for any help.

Upvotes: 0

Views: 83

Answers (1)

furas
furas

Reputation: 143098

You can assign label to (global) variable

label_energy = Label(...)

and then you can change

energy += 10

label_energy['text'] = str(energy)
#or
label_energy.config(text=str(energy))

But Tkinter has special variables IntVar, StringVar, etc. and you can use it with label using textvariable=

 energy = IntVar()
 energy.set( 0 )

 Label(..., textvariable=energy )

If you change variable energy

 energy.set( energy.get() + 10 )

then label will change its text automatically.

Upvotes: 1

Related Questions