我正在尝试编写一个程序,以便沿着屏幕移动绘制汽车,并且向上和向下箭头键可以更改汽车的速度。但是,当我按下任一键时,都不会调用任何命令。我试过将bind_all和focus线更改为self.canvas,但这也不起作用。我该如何解决?
class racingCar:
def __init__(self):
window = Tk()
window.title("Racing Car")
self.cWidth = 500
self.cHeight = 200
self.canvas = Canvas(window,width = self.cWidth,height = self.cHeight,bg = "white")
self.canvas.pack()
self.x = 0
self.y = self.cHeight
self.drawCar(self.x,self.y)
self.dx = 5
self.sleepTime = 50
self.animate()
window.bind_all("<Up>",self.increaseSpeed)
window.bind_all("<Down>",self.decreaseSpeed)
window.focus()
window.mainloop()
def drawCar(self,x,y):
self.canvas.create_rectangle(x,y - 20,x + 50,y - 10,fill = "yellow",tags = "car")
self.canvas.create_oval(x + 10,x + 20,y,fill = "black",tags = "car")
self.canvas.create_oval(x + 30,x + 40,tags = "car")
self.canvas.create_polygon([x + 10,y - 30,x + 30,y - 20],fill = "blue",tags = "car")
def increaseSpeed(self,event):
print("pressed up")
self.dx += 2.5
def decreaseSpeed(self,event):
print("pressed down")
if self.dx > 0:
self.dx -= 2.5
def animate(self):
while not self.dx == 0:
self.canvas.move("car",self.dx,0)
self.canvas.after(self.sleepTime)
self.canvas.update()
if self.x < self.cWidth + 10:
self.x += self.dx
else:
self.x = -60
self.canvas.delete("car")
self.drawCar(self.x,self.y)
racingCar()