我做了一个简单的函数来加载tkinter中的web照片。 在抓取照片时,GUI将显示提示“正在加载…”
完成后,照片将覆盖此提示。
为了避免GUI在爬行时冻结,我使用threading
模块来执行此操作
这是一个最小的、可重复的例子
import requests
import threading
import tkinter
from PIL import ImageTk,Image
from io import BytesIO
class MultiProcessGetResultWithoutArgs(threading.Thread): # get thread result
def __init__(self, func):
threading.Thread.__init__(self)
self.func = func
self.result = None
def getResult(self):
return self.result
def run(self):
self.result = self.func()
def GetOne():
return Image.open(BytesIO(requests.get('https://s2.ax1x.com/2020/02/07/12usP0.th.jpg').content))
def checkWhetherGet(): # judge whether it has result.
result = thread.getResult()
if result:
img1 = ImageTk.PhotoImage(result)
tkinter.Label(w,image=img1).grid(row=0,column=0)
w.update()
w.after_cancel(1)
else:
w.after(100,checkWhetherGet)
def about():
global w,thread
w = tkinter.Toplevel()
tkinter.Label(w,text="loading....").grid(row=0,column=0)
thread = MultiProcessGetResultWithoutArgs(GetOne)
thread.start() # non-block thread
w.after(1000,checkWhetherGet)
w.mainloop()
Win = tkinter.Tk()
tkinter.Button(Win,text="start",command=about).grid()
Win.mainloop()
现在,如果我调试这段代码,它可以显示图像。 但是如果我运行这段代码,它只会放大窗口大小,而不会显示图像
最后我发现了我的问题。就像this所说的,我保留了参考资料。
xx.image = img1
但真正让我困惑的是调试器为什么不使用垃圾收集相关问题 更多 >
编程相关推荐