[英]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.