使用tkinter在Python中显示/更新分数
我正在用tkinter图形界面做一个街机游戏,和大多数街机游戏一样,游戏需要在屏幕上显示分数,每当用户击杀一个敌人时,分数就要更新。
我现在的做法是在一个画布上创建一个文本,然后调用一个函数来创建另一个文本,这次是更新后的分数值(分数是一个全局变量)。
为了正确实现这一点,我必须先删除之前创建的文本,然后再创建新的文本,这样才能正确显示。否则(就像我现在的情况),文本会堆叠在一起,一个叠一个,乱七八糟的。
下面是代码:
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)
我知道我可以把 J
设为全局变量,但我不能这样做,因为在游戏代码中,这个函数是在另一个函数里面的,而那个函数又调用了 Toplevel()
并且隐藏了主窗口,这就意味着我不能定义全局的 J=canvas.create_text(100,100, text=("Score", Score), font=("Comic Sans", 50))
,因为如果我这样做,系统会告诉我画布还没创建。
所以有没有什么办法可以实现我想做的,而不需要使用 global J
?或者有没有其他更简单的方法?
附注:使用的是python 3.3.5 rc1
2 个回答
1
你可以使用 Label
来实现这个功能。你可以用变量文本来随时改变它的值。
我们来看一个简单的例子:
var = StringVar()
label = Label( root, textvariable=var)
var.set("Hey!? How are you doing?")
label.pack()
现在你可以随时把它设置成你喜欢的任何内容。你只需要这样做 var.set("我的文本")
。
如果需要参考,可以查看 这里
编辑:
如果你想仅使用画布来实现这个功能,可以参考这个 Bryan Oakley 的回答。
0
你可以用itemconfig来改变画布上某个项目的文字:
canvas.itemconfig(J, text=Score)
至于创建一个叫做J的全局变量……这其实和tkinter没有关系。最好的解决办法是换一种面向对象的方法,把J
作为某个类的属性。