如何同时移动两个 tkinter 小部件但异步?

问题描述

问题很直接。有什么办法可以在 canvas.move 图像 B 到左侧的同时 canvas.move 图像 A 到右侧?

我之前通过使用 multiprocessing 来运行在其上分层的多个画布来实现这一点,但这在很大程度上是我制定的一种解决方法

有没有官方/更好的方法来做到这一点?任何建议都有帮助。

解决方法

您无需做任何特别的事情。只需同时为两个对象调用 move 方法。当屏幕更新时,两者将同时更新。

例如,每次按下键盘上的空格键时,以下代码会将每个图像移动 5 个像素:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root,background="black",width=400,height=400)
canvas.pack(fill="both",expand=True)

image_a = tk.PhotoImage(width=50,height=50)
image_b = tk.PhotoImage(width=50,height=50)
image_a.put(("#ff0000",),(0,49,49))
image_b.put(("#00ff00",49))

canvas.create_image(175,200,image=image_a,tags=("image_a",))
canvas.create_image(225,image=image_b,tags=("image_b",))

def sync_move(event):
    canvas = event.widget
    canvas.move("image_a",5,0)
    canvas.move("image_b",-5,0)

canvas.bind("<space>",sync_move)
canvas.focus_set()

root.mainloop()