Вопрос

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

Это было полезно?

Решение 2

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.

Другие советы

You should use Label for this purpose. You can use variable text to change its value whenever you want.

Let's take a small example:

var = StringVar()
label = Label( root, textvariable=var)

var.set("Hey!? How are you doing?")
label.pack()

Now you can set it to anything you like anytime you want. You just need to do var.set("my text").

For reference you can look here

Edit:

If you wanna do it using canvas only then you can refer to this Bryan Oakley answer.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top