I make a simple function to load a web photo in tkinter. When it is crawling a photo,the GUI will show a tip "loading...".
When it finishes,then the photo will cover this tip.
For avoiding GUI freezing when it is crawling,I use threading
module to do this.
Here is a Minimal, Reproducible Example.
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()
Now if I debug this code,it can show the image. But if I run this code,it will only enlarge the window size but not show the image.
Finally I find my problem.Like this said,I keep reference.
xx.image = img1
And solve my problem.But what really makes me confused is that why debugger won't use garbage collection.