gpt4 book ai didi

python-3.x - Tkinter 图像应用程序在运行后一直卡住系统

转载 作者:行者123 更新时间:2023-12-04 19:05:41 29 4
gpt4 key购买 nike

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

#!/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] 打开一张图像的能力。

最佳答案

加载图像可能需要时间并导致卡住。最好运行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因为不推荐通配符导入。

关于python-3.x - Tkinter 图像应用程序在运行后一直卡住系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70515842/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com