我试图一个接一个地移动两个图像,但两个图像同时开始移动。基本上,我想要的是等到Image1到达目的地然后Image2开始移动。这是我的代码
import tkinter as tk
from PIL import ImageTk
from PIL import Image
import time
class gui(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.canvas = tk.Canvas(parent, bg="blue", highlightthickness=0)
self.canvas.pack(fill="both", expand=True)
self.img = tk.PhotoImage(file="Club14.gif")
self.card1 = self.canvas.create_image(0, 0, image=self.img, anchor="nw")
self.card2= self.canvas.create_image(800, 800, image=self.img, anchor="nw")
self.move_object(self.canvas, self.card1, [400, 410], 8)
self.move_object(self.canvas, self.card2, [400, 440], 8)
def move_object(self, canvas, object_id, destination, speed=50):
dest_x, dest_y = destination
coords = self.canvas.coords(object_id)
current_x = coords[0]
current_y = coords[1]
new_x, new_y = current_x, current_y
delta_x = delta_y = 0
if current_x < dest_x:
delta_x = 1
elif current_x > dest_x:
delta_x = -1
if current_y < dest_y:
delta_y = 1
elif current_y > dest_y:
delta_y = -1
if (delta_x, delta_y) != (0, 0):
canvas.move(object_id, delta_x, delta_y)
if (new_x, new_y) != (dest_x, dest_y):
canvas.after(speed, self.move_object, canvas, object_id, destination, speed)
if __name__ == "__main__":
root = tk.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
gui(root)
root.mainloop()
答案 0 :(得分:0)
要移动画布的项目顺序,您可以将它们放在列表中并定义一个方法,例如下面的run_move_sequence()
,只有在前一个项目到达后才开始移动每个项目目的地:
import tkinter as tk
class gui(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(parent, width=200, height=200)
self.canvas.pack(fill="both", expand=True)
self.objects = [self.canvas.create_oval(10, 10, 30, 30, fill="blue"),
self.canvas.create_rectangle(170, 170, 190, 190, fill="yellow") ]
self.destinations = [ [90, 75], [90, 100] ]
self.speed = 20
self.start_move_sequence()
def start_move_sequence(self):
self.moveDone = False
self.count = 0
self.run_move_sequence()
def run_move_sequence(self):
if self.moveDone == False:
self.move_object(self.objects[self.count], self.destinations[self.count])
self.canvas.after(self.speed, self.run_move_sequence)
else:
# Start run_move_sequence on the next object
self.count += 1
if self.count < len(self.objects):
self.moveDone = False
self.run_move_sequence()
def move_object(self, object_id, destination):
dest_x, dest_y = destination
coords = self.canvas.coords(object_id)
current_x, current_y = coords[0], coords[1]
new_x, new_y = current_x, current_y
delta_x = delta_y = 0
if current_x < dest_x:
delta_x = 1
elif current_x > dest_x:
delta_x = -1
if current_y < dest_y:
delta_y = 1
elif current_y > dest_y:
delta_y = -1
if (delta_x, delta_y) != (0, 0):
self.canvas.move(object_id, delta_x, delta_y)
if (new_x, new_y) == (dest_x, dest_y):
self.moveDone = True
if __name__ == "__main__":
root = tk.Tk()
gui(root)
root.mainloop()