我正在做一個玩具專案來學習 tkinter 的基礎知識。
我有一個帶有np.array物件位置和速度的 Drone 類,它會在每個增量更新自身。位置在 0 和 1 之間浮動,然后乘以高度/寬度。
我現在想看到這個 Drone 在螢屏上移動,所以我使用了window.after()和window.update()方法。
這是我寫的代碼:
import tkinter as tk
import numpy as np
def update_drone(canv, drone):
# update the coords of all the polygon objects with new position (scaled to screen dimensions)
canv.coords(canv.find_withtag("drone"), *([WIDTH, HEIGHT] * drone.position))
def game_loop(window, canvas, dr):
delta = 0.01
# function which updates drone's attributes
dr.update(delta)
# built in sleep
sleep(delta)
#update drone function from above
update_drone(canvas, dr)
canvas.pack()
# if the drone isnt below the screen, call the game loop next delta
if dr.position[1] < 1:
window.after(int(delta * 1000), game_loop, window, canvas, dr)
if __name__ == "__main__":
# set up window
window = tk.Tk()
window.maxsize(WIDTH, HEIGHT)
window.minsize(WIDTH, HEIGHT)
window.configure(bg="black")
# height and width are global variables i define
canvas = tk.Canvas(window, bg="black", height=HEIGHT, width=WIDTH)
# create Drone object
dr = Drone()
# call draw drone function which is defined below
draw_drone(canvas, dr)
window.after(0, game_loop, window, canvas, dr)
# main loop
window.mainloop()
draw_drone我上面呼叫的函式初始化兩個多邊形:
def draw_drone(canv: tk.Canvas, drone: Drone) -> None:
pos_x, pos_y = WIDTH * drone.position[0], HEIGHT * drone.position[1]
# draw drone body
size = 20
canv.create_polygon(
[
pos_x - size,
pos_y - size,
pos_x - size,
pos_y size,
pos_x size,
pos_y size,
pos_x size,
pos_y - size,
],
outline="white",
fill="yellow",
width=3,
tags="drone",
)
canv.create_polygon(
[
pos_x,
pos_y 0.8 * size,
pos_x - 0.8 * size,
pos_y,
pos_x,
pos_y - 0.8 * size,
pos_x 0.8 * size,
pos_y,
],
outline="red",
fill="grey",
width=8,
tags="drone",
)
當我運行上面的代碼時,游戲回圈被呼叫(當我列印出無人機位置的值時,它們確實相應地更新了)但是畫布在第一幀上被凍結并且永遠不會更新。
如果有人能告訴我問題是什么,我將不勝感激!
編輯 :
這是我使用的基本無人機類:
class Drone:
def __init__(self):
self.position = np.array([0.5, 0.5])
self.velocity = np.array([0, 0])
self.forces = np.array([0, 0])
def update(self, dt):
self.velocity = dt * (self.forces np.array([0, 1])) # forces gravity
self.position = self.velocity * dt
uj5u.com熱心網友回復:
最后我的錯誤很簡單。我不明白如何canvas.coords真正起作用。我的update_drone函式的正確代碼實際上是:
for t in canvas.find_withtag("drone"):
canv.coords(t, *([WIDTH, HEIGHT] * drone.position))
代替
canv.coords(canv.find_withtag("drone"), *([WIDTH, HEIGHT] * drone.position))
這正確地更新了坐標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/393614.html
標籤:Python 特金特 帆布 窗户 tkinter-canvas
