繁体   English   中英

如何在不影响 tkinter GUI 的情况下在后台运行代码?

[英]How to run code on background without affecting the tkinter GUI?

我正在开发一个使用 tkinter 作为图像查看器的 GUI。 工作流程是我们 select 一个带有菜单栏中“新图像”选项的图像,该选项在 canvas 中显示所选图像,并创建一个小的 window,其中包含显示所有图像的行和列的当前文件夹。 我面临的问题是,加载文件夹中的所有图像大约需要 6 秒,并且仅在 6 秒之后,所选图像才会显示在 canvas 上。 我想先显示选定的图像,然后像后台进程一样将图像加载到文件夹中。 这是代码self.drawImage()-在canvas上显示图像(self.image),self.folderImg()-从路径(self.path)加载所有图像并在行和列中显示window

  def newImage(self):

        self.imageName= filedialog.askopenfilename()
        filetype=""
        try: filetype=imghdr.what(self.imageName)
        except:
           messagebox.showinfo(title="Image File",message="Choose an Image File!" , parent=self.master)
        self.path=os.path.split(self.imageName)[0]

        if filetype in ['jpeg', 'bmp', 'png', 'tiff']:            
            im= PIL.Image.open(self.imageName)
            self.image=im
            self.originalImage=im.copy()
            self.imageSize=im.size

            self.imageForTk=self.makeImageForTk()   
            self.drawImage()            
            self.folderImg()

我阅读了一些帖子并得出结论,线程将起作用,所以我将“self.folderImg()”更改为

t1=threading.Thread(target=self.folderImg)
t1.start()

当我将它放在“self.image=im”行之后它不起作用,它给出了与之前类似的结果,但是当我把它放在最后一行时,我得到了 output,我希望在 6 点前后显示 canvas 图像仅显示文件夹图像的秒数,但在这 6 秒内,GUI 被卡住并且没有响应,无法按下任何按钮。 请提供一个解决方案,以更短的时间或不影响 GUI 功能的情况下加载文件夹图像

最终代码

  def newImage(self):

        self.imageName= filedialog.askopenfilename()
        filetype=""
        try: filetype=imghdr.what(self.imageName)
        except:
           messagebox.showinfo(title="Image File",message="Choose an Image File!" , parent=self.master)
        self.path=os.path.split(self.imageName)[0]

        if filetype in ['jpeg', 'bmp', 'png', 'tiff']:            
            im= PIL.Image.open(self.imageName)
            self.image=im
            self.originalImage=im.copy()
            self.imageSize=im.size
            self.imageForTk=self.makeImageForTk()   
            self.drawImage()

            t1=threading.Thread(target=self.folderImg)
            t1.start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM