所以我试图制作一个定时循环,在屏幕上显示不同的文本命令,用户必须按下与文本命令对应的键。问题是,由于文本居中,它只是在自己上面绘制,直到命令无法读取。有没有一种方法可以在每次我想在窗口中绘制文本时清除窗口?我在下面发布了我当前的代码
from Graphics import *
from Myro import timer #used for the animation.
import random #random starting positions and speeds
NUMBALLS = 10
WINSIZE = 500
done = 0
win = Window("GAME", WINSIZE, WINSIZE)
#win.mode = "manual" #Trick to make the animation smoother....
space = Text((180, 250), "SPACEBAR")
space.fill = Color("blue")
space.fontSize = 30
space.xJustification = "bottom"
space.yJustification = "bottom"
up = Text((180, 250), "UP")
up.fill = Color("red")
up.fontSize = 30
up.xJustification = "bottom"
up.yJustification = "bottom"
down = Text((180, 250), "DOWN")
down.fill = Color("black")
down.fontSize = 30
down.xJustification = "bottom"
down.yJustification = "bottom"
left = Text((180, 250), "LEFT")
left.fill = Color("green")
left.fontSize = 30
left.xJustification = "bottom"
left.yJustification = "bottom"
right = Text((180, 250), "RIGHT")
right.fill = Color("orange")
right.fontSize = 30
right.xJustification = "bottom"
right.yJustification = "bottom"
shape = Rectangle((0, 500), (500, 0))
shape.fill = Color("white")
keys = (space,up,left,right,down)
def handleKeyPress(win, event):
global done
if ((this == 0) and (done == 0)):
if (event.key == "space"):
print("correct")
done = 1
if ((this == 1) and (done == 0)):
if (event.key == "Up"):
print("correct")
done = 1
#if ((this == 2) and (done == 0)):
# if (event.key == "Left"):
# print("correct")
# done = 1
#if ((this == 3) and (done == 0)):
# if (event.key == "Right"):
# print("correct")
done = 1
# if ((this == 4) and (done == 0)):
# if (event.key == "Down"):
# print("correct")
# done = 1
for i in timer(5):
shape.draw(win)
this = random.randint(0,4)
me = keys[this]
me.draw(win)
onKeyPress(handleKeyPress)
print("done")
wait(0.4)
done = 0
EDIT:令人惊讶的是,您使用的是Calico图形,它是基于IronPython而非Cython构建的,并且无法访问tkinter绑定。底层实现是Gtk,而不是tkinter,如果您正在尝试扩展功能(尽管它看起来完全足够),那么就在这里查看。在这种情况下,简短的答案是window.clear()。
据我所知,"Graphics"并不是一个标准的Python包。我在Python 2和3上收到导入错误。然而,我相信"Zelle"图形是一个非常标准的Python学习库,而且你看起来像在学习,所以我猜graphics==Zelle graphics
也就是说,我将更笼统地回答这个问题,而不是针对那个特定的包,它在规范Python中并没有真正使用。
Graphics构建在tkinter上,这是Python和tk之间一个非常强大的底层接口。Graphics画布实际上是一个tkinter画布实例。
以下是关于tkinter画布对象的effbot文档:
http://effbot.org/tkinterbook/canvas.htm
它非常清晰易用——你会注意到有
my_canvas.delete('all')
my_canvas.create_text(0,0,text='whatever')
解决您的问题。
转到Zelle图形的源代码,它非常简单,看看画布隐藏在哪里。然后直接在上面调用方法。它会给你更多的功能,成为一个更可扩展的解决方案,并让你能够轻松地使用更强大的工具!
这是Zelle图形的代码:
http://mcsp.wartburg.edu/zelle/python/graphics.py
你会注意到,所有Graphics实例都引用了"self.canvas"。它甚至没有隐藏(在变量名上用"__"前缀表示),所以你可以直接访问画布,对它做任何你想做的事情。为了获得最简单的解决方案,我们可能会注意到,您也可以在单个文本对象上使用"setText",而不是使多个文本对象相互替换。