我正在使用 Tkinter 创建一个形状,我的目标是不断将形状移动到 canvas 的右侧,直到离开屏幕(并重复)

I'm using Tkinter to create a shape and my goal is to continuously move the shape to the right of canvas until off screen ( AND REPEAT)

请原谅缺少文档。我是新手,所以我的代码不是最好的,但我总是很感激积极的反馈。所以我的问题是试图在 canvas 出现后将形状 return 恢复到原始起始位置并不断重复该过程。有什么建议么?另外,有没有办法可以将向上和向下箭头键绑定到 increase/decrease 形状的速度?

#import all from tkinter module
from tkinter import *

#create RacingCar class        
class RACECAR:
    
    def __init__(self):
        
        window = Tk()
        window.title("Racing Car")
        self.x = 1
        self.y = 0

        self.canvas = Canvas(window, width = 1200, height = 400, bg = "white")
        self.canvas.pack()
        self.displayCar()


        window.mainloop()

    def displayCar(self):
        
        self.body = self.canvas.create_rectangle(0, 300, 150, 350, tags = "rect", \
            fill = "black")
        self.wheel1 = self.canvas.create_oval(100, 350, 150, 400, tags = "oval", \
            fill = "black")
        self.wheel2 = self.canvas.create_oval(0, 350, 50, 400, tags = "oval", \
            fill = "black")
        self.hood = self.canvas.create_rectangle(0, 250, 100, 300, tags = "rect", \
            fill = "black")
        self.movement()


    def movement(self):
       
        self.canvas.move(self.body, self.x, self.y)
        
        self.canvas.move(self.wheel1, self.x, self.y)
        
        self.canvas.move(self.wheel2, self.x, self.y)
        
        self.canvas.move(self.hood, self.x, self.y)
        
        self.canvas.after(100, self.movement)


RACECAR()

你可以给汽车的四件物品贴上一个共同的标签,然后

  • 使用通用标签保存小车的起始位置
  • 使用公共标签移动汽车而不是移动每个项目
  • 通过检查canvas.coords(...)的第一个值检查小车是否出canvas,如果是则将小车移回其起始位置
def displayCar(self):
    # assign common tag "car" to items
    self.body = self.canvas.create_rectangle(0, 300, 150, 350, tags="car rect", fill="black")
    self.wheel1 = self.canvas.create_oval(100, 350, 150, 400, tags="car oval", fill="black")
    self.wheel2 = self.canvas.create_oval(0, 350, 50, 400, tags="car oval", fill="black")
    self.hood = self.canvas.create_rectangle(0, 250, 100, 300, tags="car rect", fill="black")
    # save the starting position
    self.start_pos = self.canvas.coords("car")[:2] 
    self.movement()

def movement(self):
    self.canvas.move("car", self.x, self.y)
    bbox = self.canvas.coords("car")
    if bbox[0] > 1200:
        # car moved out of canvas, so restart at starting position
        self.canvas.moveto("car", self.start_pos[0], self.start_pos[1])
    self.canvas.after(100, self.movement)

调整速度,可以绑定<Up><Down>,在回调中更新self.x

def __init__(self):
    ...
    self.inc_x = 1   # adjust the value to suit your case
    window.bind('<Up>', lambda e: self.set_speed(+self.inc_x))
    window.bind('<Down>', lambda e: self.set_speed(-self.inc_x))
    ...

def set_speed(self, inc):
    self.x += inc
    # make sure self.x is at least 1 (or other value you want)
    if self.x < 1:
        self.x = 1