[英]Moving object on canvas python
我想讓一個小方塊每 3 秒向左移動 10 個像素,我的代碼如下。 我不確定為什么它只移動一次。 一些幫助將不勝感激!
import tkinter as tk
import time
root = tk.Tk()
WIDTH = HEIGHT = 400
x1 = y1 = WIDTH / 2
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10)
def draw_rect():
global c2
canvas.delete(c2)
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
def del_rect():
canvas.delete(c1)
#canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="white", opacity=0.5)
while 1:
root.update()
time.sleep(3)
del_rect()
x1 -= 10
draw_rect()
root.mainloop()
mainloop()
運行循環,直到你關閉 window - 所以它阻塞所有循環並且它只執行一次並且它只移動一次矩形。 在您的版本中,您應該刪除mainloop()
並且它不會阻止它 - 因為您在循環中使用update()
所以它會正確運行。
但你可以用不同的方式做到這一點。
您可以使用root.after(3000, draw_rect)
) 在 3 秒后執行draw_rect()
。 並且draw_rect()
應該再次運行root.after(3000, draw_rect)
以在另外 3 秒后再次運行它 - 這樣它將循環並且不會被mainloop()
阻塞( mainloop()
將每 3 秒運行一次draw_rect()
)
Canvas
有 function move(object, dx, dy)
所以你不必刪除矩形並再次創建它。
我使用300ms
來更快地運行它。
import tkinter as tk
# --- constants --- (PEP8: UPPER_CASE_NAMES)
WIDTH = 400
HEIGHT = 400
# --- functions ---
def move_rect():
canvas.move(c1, -10, 0) # move left
canvas.move(c2, 10, 0) # move right
# run again after 300ms
root.after(300, move_rect) # 300ms = 0.3s # I use smaller value to make it faster
# --- main ---
x1 = y1 = WIDTH / 2
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="red")
# run first time after 300ms
root.after(300, move_rect) # 300ms = 0.3s # I use smaller value to make it faster
root.mainloop()
編輯:
當矩形靠近邊界時,使用變量speed1
, speed2
改變方向的版本。
import tkinter as tk
# --- constants --- (PEP8: UPPER_CASE_NAMES)
WIDTH = 400
HEIGHT = 400
# --- functions ---
def move_rect():
global speed1
global speed2
#x1, y1, x2, y2 = canvas.coords(c1)
pos = canvas.coords(c1)
if speed1 < 0 :
if pos[0] < 10:
speed1 = -speed1
else:
if pos[2] > WIDTH-10:
speed1 = -speed1
#x1, y1, x2, y2 = canvas.coords(c2)
pos = canvas.coords(c2)
if speed2 < 0:
if pos[0] < 10:
speed2 = -speed2
else:
if pos[2] > WIDTH-10:
speed2 = -speed2
canvas.move(c1, speed1, 0) # move left
canvas.move(c2, speed2, 0) # move right
# run again after 30ms
root.after(30, move_rect) # 30ms = 0.03s - I uses smaller value to make it faster
# --- main ---
x1 = y1 = WIDTH / 2
speed1 = -10
speed2 = +10
root = tk.Tk()
canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()
print(dir(canvas))
c1 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="green")
c2 = canvas.create_rectangle(x1, y1, x1 + 10, y1 + 10, fill="red")
# run first time after 300ms
root.after(300, move_rect) # 300ms = 0.3s - I uses smaller value to make it faster
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.