Elxas866
Elxas866

Reputation: 1

Python constantly update label in tkinter

I'm making some kind of cookie clicker game with Tkinter to practise my Python skills.

This is my code so far:

"""
author: Elxas866
file: BubbleClicker.py
descr.: A cookie clicker-like game
"""


from tkinter import *
from PIL import ImageTk, Image


clicks = 0
def counter():
    global clicks
    clicks += 1
    print(clicks)

def main():

    root = Tk()

    root.minsize(500, 500) #pixels
    root.title("Bubble Cliker")

    bubble = Image.open("assets/Bubble.png")
    Bubble = ImageTk.PhotoImage(bubble)

    image = Button(image=Bubble, command=counter)
    image.pack()
    image.place(relx=0.5, rely=0.5, anchor=CENTER)

    score = Label(text=clicks, font=("Arial", 25))
    score.pack()

    root.mainloop()

main()#call

Everything works perfectly fine, but it doesn't show my score in the label. It updates it if I print it so technically it works. But in the label it stays 0. Do you now how to fix that?

Thanks in advance!

Upvotes: 0

Views: 195

Answers (2)

Elxas866
Elxas866

Reputation: 1

Final function:

def counter():
    global clicks
    clicks += 1
    score.config(text=clicks)

Correct code:

"""
author: Elxas866
file: BubbleClicker.py
descr.: A cookie clicker-like game
"""


from tkinter import *
from PIL import ImageTk, Image


clicks = 0
def counter():
    global clicks
    clicks += 1
    score.config(text=clicks)
    print(clicks)

def main():

    root = Tk()

    root.minsize(500, 500) #pixels
    root.title("Bubble Cliker")

    bubble = Image.open("assets/Bubble.png")
    Bubble = ImageTk.PhotoImage(bubble)

    image = Button(image=Bubble, command=counter)
    image.pack()
    image.place(relx=0.5, rely=0.5, anchor=CENTER)

    global score
    score = Label(text=clicks, font=("Arial", 25))
    score.pack()

    root.mainloop()

main()#call

Upvotes: 0

IJ_123
IJ_123

Reputation: 507

In the counter() function, after clicks += 1, add score.config(text=score)

So the final function looks like this:

def counter():
    global clicks
    clicks += 1
    score.config(text=score)

Also, just a suggestion: Avoid importing everything from a module.

Upvotes: 1

Related Questions