【问题标题】:Tkinter image application keeps freezing system after it runsTkinter 图像应用程序在运行后一直冻结系统
【发布时间】:2021-12-29 06:26:04
【问题描述】:

我正在使用以下代码测试一个应用程序:

#!/usr/bin/env python3
import os
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk

root = Tk()
root.title("Image Viewer App")
root.withdraw()
location_path = filedialog.askdirectory()
root.resizable(0, 0)

#Load files in directory path
im=[]
def load_images(loc_path):
    for path,dirs,filenames in os.walk(loc_path):
        for filename in filenames:
            im.append(ImageTk.PhotoImage(Image.open(os.path.join(path, filename))))

load_images(location_path)
root.geometry("700x700")
#Display test image with Label
label=Label(root, image=im[0])
label.pack()
root.mainloop()

问题是当我运行它时,我的系统会死机,Linux 发行版会崩溃。我无法说出我做错了什么,除非我不确定将整个图像存储在列表变量中与仅存储位置本身是否是一个好主意。目前,它只是测试使用 img=[0] 打开一张图片的能力。

【问题讨论】:

    标签: python-3.x ubuntu tkinter python-imaging-library


    【解决方案1】:

    图像的加载可能需要一些时间并导致冻结。最好在子线程中运行load_images()

    import os
    import threading
    import tkinter as tk
    from tkinter import filedialog
    from PIL import Image, ImageTk
    
    root = tk.Tk()
    root.geometry("700x700")
    root.title("Image Viewer App")
    root.resizable(0, 0)
    root.withdraw()
    
    #Display test image with Label
    label = tk.Label(root)
    label.pack()
    
    location_path = filedialog.askdirectory()
    root.deiconify()  # show the root window
    
    #Load files in directory path
    im = []
    def load_images(loc_path):
        for path, dirs, filenames in os.walk(loc_path):
            for filename in filenames:
                im.append(ImageTk.PhotoImage(file=os.path.join(path, filename)))
        print(f'Total {len(im)} images loaded')
    
    if location_path:
        # run load_images() in a child thread
        threading.Thread(target=load_images, args=[location_path]).start()
    
        # show first image
        def show_first_image():
            label.config(image=im[0]) if len(im) > 0 else label.after(50, show_first_image)
    
        show_first_image()
    
    root.mainloop()
    

    请注意,我已将 from tkinter import * 更改为 import tkinter as tk,因为不建议导入通配符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-04
      • 2015-04-16
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多