我正在使用以下代碼測驗應用程式:
#!/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] 打開一張影像的能力。
uj5u.com熱心網友回復:
影像加載可能需要時間并導致凍結。最好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如不建議通配符進口。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/398962.html
