如果我调试或运行它,为什么会有两种不同的结果?

2024-09-30 08:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个简单的函数来加载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()

现在,如果我调试这段代码,它可以显示图像。 但是如果我运行这段代码,它只会放大窗口大小,而不会显示图像


Tags: importselftkinterdefguiresultrequeststhread

热门问题