使用tkinter在python上显示/更新分数

时间:2014-04-29 08:55:37

标签: python tkinter refresh screen

我正在使用tkinter gui进行街机游戏,就像大多数拱廊一样,需要在屏幕上显示分数,每次用户杀死敌人时都会更新(显然)。

我是通过在画布上创建文本并调用创建另一个文本的函数来实现的,但这次更新了得分值(Wich是一个全局变量)。

所以,要以正确的方式做到这一点,我必须删除之前创建的文本,然后创建新文本以便正确显示,因为否则(这是我的情况)它将是就像一堆文本一个在另一个上面,等等......

所以这是代码:

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 appereance 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 supossed to work deleting the "J" everytime 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)

所以我知道我可以将J作为全局变量,但我不能这样做,因为在游戏代码中,函数位于另一个调用{{1并且执行主窗口的Toplevel(),这意味着我无法定义全局withdraw(),因为如果我这样做,它会告诉我尚未创建的画布。

有没有办法做我想做的事情,而不必使用J=canvas.create_text(100,100, text=("Score", Score), font=("Comic Sans", 50))?或者其他更简单的方法吗?

谢谢!

顺便说一句,请原谅我的英雄技能......我知道他们很糟糕。

PD:使用python 3.3.5 rc1

2 个答案:

答案 0 :(得分:1)

您应该使用Label来实现此目的。您可以随时使用变量文本更改其值。

我们举一个小例子:

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

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

现在,您可以随时set随意添加任何内容。您只需要执行var.set("my text")

作为参考,您可以查看here

编辑:

如果您只想使用画布,那么您可以参考此Bryan Oakley答案。

答案 1 :(得分:0)

您可以使用itemconfig更改画布项目中的文本:

canvas.itemconfig(J, text=Score)

至于创建名为J的全局变量...这不是与tkinter相关的问题。最好的解决方案是切换到面向对象的方法,其中J是某个类的属性。