Skip to content
Advertisement

Display/Update score on python using tkinter

I’m making an arcade game using tkinter GUI, that as most arcades, needs a score display on screen that updates every time the user kills an enemy (obviously).

I am doing it by creating a text on a canvas, and calling a function that creates another one, but this time with the score value (Which is a global variable) updated.

So, to do that in the right way, I must delete the text that has been created before and then create the new one in order for it to be displayed correctly, because otherwise (Which is my case) It’ll be like a stack of text one over the other, and other, etc…

So here’s the code:

from tkinter import *

Root= Tk()
canvas= Canvas(Root,width=500, height=500, bg="white")
canvas.pack()

Score= 0 #This is the global with the score value

J=canvas.create_text(100,100, text=("Score", Score), font=("Comic Sans", 50)) #This is the first appearance of the score on screen, or the first creation.

def change(): #Here's where I change the score value and create the new text
    global Score
    Score+=1
    J=canvas.create_text(100,100, text=("Score", Score), font=("Comic Sans", 50))

def changee(): #And this one, is supposed to work deleting the "J" every time it is called, but it only works the first time it is called with the first text
    canvas.delete(J)
    print("del")

def do(): #This one calls the other two in a button (Because I need to call them like this on the actual game code
    change()
    changee()

B= Button(canvas, text= "change it", command=do) 
B.place(x=300,y=300)

So I know I just could put the J as a global variable, but I can’t do that, because on the game code the function is inside another function which is the one that calls a Toplevel() and does a withdraw() of the main window, and that means I cant define a global J=canvas.create_text(100,100, text=("Score", Score), font=("Comic Sans", 50)) because if I do, it’ll tell me that canvas its not yet created.

So is there any way to do what I am trying to do, without having to use a global J? or any other easier way to do it?

PD: Using python 3.3.5 rc1

Advertisement

Answer

You can use the itemconfig to change the text in the canvas item:

canvas.itemconfig(J, text=Score)

As far as creating a global variable named J… this isn’t an issue related to tkinter. The best solution is to switch to an object-oriented approach, where J is an attribute of some class.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement