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:

JavaScript

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:

JavaScript

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