下述代码:
from tkinter import *
import random
import time
class SnakeHead:
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.x = -3
self.y = -3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
self.curPos = self.canvas.coords(self.id)
self.prePos = None
def move_ball(self):
self.canvas.move(self.id,self.x,self.y)
pos = self.canvas.coords(self.id)
if self.curPos != pos:
self.prePos = self.curPos
self.curPos = pos
print("----------") #调试
print(self.curPos)
print(self.canvas.winfo_height())
print(self.prePos)
print("----------")
if self.curPos[0] <= 0:
self.x = 3
if self.curPos[2] >= self.canvas_width:
self.x = -3
if self.curPos[1] <= 0:
self.y = 3
if self.curPos[3] >= self.canvas_height:
self.y = -3
self.canvas.after(100,self.move_ball)
root = Tk()
root.title("Game")
root.resizable(0,0)
root.wm_attributes("-topmost",1)
canvas = Canvas(root,width=500,height=400,bd=0,highlightthickness=0)
canvas.pack()
#print("heigt:")
#print(canvas.winfo_height())
# test
sh = SnakeHead(canvas,'red')
sh.move_ball()
root.mainloop()
运行后,print(self.canvas.winfo_height())
前2次的循环返回值为1,而不是实际的400,运行结果如下图所示,
这是一个问题。若不解决,则小球的动画演示不正确,其运动会越出边界。
通过网上查找资料,加上自己的思考,最终的问题出在Canvas
在创建后一定要及时对主窗口执行update
命令。具体来说:上述的canvas.pack()
后添加代码:
root.update() # key code
这个问题,困扰了我断断续续2个晚上,加上我大量的思考,终于得以解决。实际上若不是动画类的程序,不及时root.update()
也是可以的。