簡體   English   中英

按鍵按下事件不會更新 while 循環內的變量

[英]Key down event does not update variable inside while loop

我目前正在使用 tkinter 和 python 在畫布上制作動畫並遇到一些問題。 我的代碼的相關部分如下。

k = 0
dirX, dirY = 1, 0

def LeftButton(event):
    dirX = -abs(dirX)

c.bind("<Left>", LeftButton)

while 1:
    k %= 6
    #show one frame of animation and hide the rest
    c.itemconfig(pc[k], state=tk.NORMAL)
    c.itemconfig(pc[(k+1) % 6], state=tk.HIDDEN)
    c.itemconfig(pc[(k+2) % 6], state=tk.HIDDEN)
    c.itemconfig(pc[(k+3) % 6], state=tk.HIDDEN)
    c.itemconfig(pc[(k+4) % 6], state=tk.HIDDEN)
    c.itemconfig(pc[(k+5) % 6], state=tk.HIDDEN)
    #move all of the frames to the same location
    c.move(pc[k],dirX*5,dirY*5)
    c.move(pc[(k+1) % 6],dirX*5,dirY*5)
    c.move(pc[(k+2) % 6],dirX*5,dirY*5)
    c.move(pc[(k+3) % 6],dirX*5,dirY*5)
    c.move(pc[(k+4) % 6],dirX*5,dirY*5)
    c.move(pc[(k+5) % 6],dirX*5,dirY*5)
    
    k += 1
    #update the canvas
    c.update()
    time.sleep(.075)

基本上, pc是畫布上圖像對象的 numpy 數組,每個索引處是動畫的不同圖像幀。 每 0.075 秒顯示一幀並隱藏所有其他幀,然后增加所有幀的位置。 我正在嘗試構建它,以便當我按下左鍵時, dirX變為負數,因此我的動畫向左移動。 動畫工作正常,但問題是 while 循環之外的任何內容都是固定的,即按下按鈕什么也不做。 可能是我綁定錯誤,但我將它綁定到我以前做過的鼠標點擊,但它仍然不起作用。 有沒有比 while 循環更好的動畫方式?
我考慮的一種方法是代替while 1: I can put while not (code for keydown event): ,但我不知道 keydown 事件的代碼,我只希望變量dirX更新然后重新啟動 while循環,這也是有問題的。 我能解決這個問題的最好方法是什么? 謝謝
編輯
我運行了一個測試,看看如果觸發事件, LeftButton是否會打印任何內容,但它沒有。 我認為這意味着當代碼在 while 循環中運行時,它不會檢查或處理事件。

在 GUI 程序中,您已經有了主mainloop ,任何額外的無限運行循環都會阻塞應用程序。
相反,請嘗試使用 tkinter 的after函數。

def animation():
    # your itemconfig, move commands and
    # other animation logic.
    c.after(75, animation)

# start animation
animation()

這將告訴 tkinter 繼續主循環,並在 75 毫秒后再次調用動畫函數。 after通常從root小部件調用,但您的畫布小部件也應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM