首先,请看一下我之前的帖子:Tkinter 理解主循环 https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop
遵循那里的建议后,在 GUI 编程中,必须不惜一切代价避免无限循环,以保持小部件响应用户输入。
而不是使用:
while 1:
ball.draw()
root.update()
time.sleep(0.01)
我设法使用self.canvas.after(1, self.draw)
在我里面draw()
功能。
所以我的代码现在看起来像这样:
# Testing skills in game programming
from Tkinter import *
root = Tk()
root.title("Python game testing")
root.resizable(0, 0)
root.wm_attributes("-topmost", 1)
canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
root.update()
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
self.canvas_height = canvas.winfo_height()
self.x = 0
self.y = -1
def draw(self):
self.canvas.move(self.id, self.x, self.y)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.y = 1
if pos[3] >= self.canvas_height:
self.y = -1
self.canvas.after(2, self.draw)
ball = Ball(canvas, "red")
ball.draw()
root.mainloop()
然而,里面的时间self.canvas.after()
不能正常工作...
如果设置为 1,速度非常快!如果设置为10、5甚至2,那就太慢了!
我在代码中使用上述 while 循环时没有遇到这个问题,因为time.sleep()
工作正常!
EDIT:
我现在可以报告,Tkinter 的 after 函数内的时间在我的 Windows 8.1 平板电脑和我的 Windows 8.1 笔记本电脑中无法正常工作,而在同一笔记本电脑中运行 Ubuntu 时则无法正常工作虚拟机它确实按其应有的方式工作。