[英]Python Tkinter Label not responding
我正在嘗試進行加載,如果 python tkinter 支持 GIF,它會很有幫助。 但是由於不支持,所以我將所有逐幀圖片放在連續播放時進行加載的列表中(使用assign_pic函數),然后我創建了一個label(稱為lab_loading),之后我更改了圖片200ms 通過調用 start_anim function。 我在循環中調用assign_pic function,我認為這會導致此錯誤。 請參閱下面的源代碼和我提供的視頻,以清楚地了解此問題。
視頻: https://drive.google.com/file/d/1WHwZqvd8vXz-ehXbQ_fRtrKPEyFLKrVe/view?usp=sharing
源代碼:
from time import sleep
from tkinter import Tk, Label
from PIL import ImageTk, Image
class Loading(Tk):
def __init__(self):
super().__init__()
self.title('Loading')
self.geometry('250x217')
self.address = getcwd()
self.imgs_list = []
self.loadingImgsList(self.address)
# This method Puts all the images in the list
def loadingImgsList(self, curAddress):
address = f'{curAddress}\\loading'
self.imgs_list = [(ImageTk.PhotoImage(Image.open(
f"{address}\\{i}.png"))) for i in range(1, 4)]
# This mehtod assigns the picture from the list via index (ind) number from the imgs_list list and
# updates the GUI when called.
def assign_pic(self, ind):
lab_loading.config(image=self.imgs_list[ind])
self.update_idletasks()
sleep(0.2)
def start_anim(self):
ind = 0
b = 0
while (b < 300):
if ind == 2:
ind = 0
else:
ind += 1
self.after(200, self.assign_pic, ind)
b += 1
if __name__ == "__main__":
root = Loading()
lab_loading = Label(root, image='')
lab_loading.pack()
root.start_anim()
root.mainloop()
我試圖讓 start_anime function 遞歸,但它仍然是一樣的。 我不知道為什么會這樣。 我也使循環有限,但它仍然無法正常工作。 因此,我們將不勝感激這個問題的解決方案,甚至是更好的建議。
你不應該在 tk 中使用 sleep,因為它會阻止 python 處理用戶操作。
the way you do animation in tk is by using the after
method, to call a function that would update the canvas, this function will call after
again, until the animation is complete.
# everything before this function should be here
self.ind = 0 #somewhere in __init__
def assign_pic(self):
if self.ind < len(imgs_list):
lab_loading.config(image=self.imgs_list[self.ind])
self.ind += 1
root.after(500,self.assign_pic) # time in milliseconds
else:
print("done") # do what you want after animation is done
if __name__ == "__main__":
root = Loading()
lab_loading = Label(root, image='')
lab_loading.pack()
root.after(100,root.assign_pic)
root.mainloop()
after
function 在一定的延遲后調度給定的 function,在此期間 GUI 可以自由響應任何操作。
編輯: after
方法以毫秒而不是秒為單位接受參數之后,我在其中輸入了幾秒而不是毫秒,現在它已經修復了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.