簡體   English   中英

Tkinter-無法同時打開多張照片(Python)

[英]Tkinter - can't open multiple photos at the same time (Python)

我試圖在Python中同時打開多張照片:

import Tkinter as tk
import os
from PIL import Image, ImageTk

root = tk.Tk()
tk.Label(root, text="this is the root window").pack()
root.geometry("200x200")

for i in range(1, 6):
    loc = os.getcwd() + '\pictures\pic%s.jpg'%(i)
    img = Image.open(loc)
    img.load()
    photoimg = ImageTk.PhotoImage(img)
    window = tk.Toplevel()
    window.geometry("200x200")
    tk.Label(window, text="this is window %s" % i).pack()

root.mainloop()

它會根據需要打開5個窗口(不包括根窗口),但圖片不會顯示。 建議? 提前Thnx

您需要在窗口上添加帶有參數image=photoimg的標簽,以顯示圖像。

您的代碼:

import Tkinter as tk
import os
from PIL import Image, ImageTk

root = tk.Tk()
tk.Label(root, text="this is the root window").pack()
root.geometry("200x200")

for i in range(1, 6):
    loc = os.getcwd() + '\pictures\pic%s.jpg'%(i)
    img = Image.open(loc)
    img.load()
    photoimg = ImageTk.PhotoImage(img)
    window = tk.Toplevel()
    window.geometry("200x200")
    tk.Label(window, text="this is window %s" % i).pack()
    tk.Label(window, image=photoimg).pack()

root.mainloop()

像喬納·弗萊明(Jonah Fleming)所說的那樣,添加image=photoimg ,您必須保留對每個PhotoImage的引用,否則當將photoimg變量分配給另一個PhotoImage時, photoimg它們進行垃圾回收。 繞過此問題的最簡單方法是將PhotoImage實例保留在列表中。 可以這樣做:

import Tkinter as tk
import os
from PIL import Image, ImageTk

root = tk.Tk()
tk.Label(root, text="this is the root window").pack()
root.geometry("200x200")

photoimage_list = [] # Create a list to hold the PhotoImages!

for i in range(1, 6):
    loc = os.getcwd() + '\pictures\pic%s.jpg'%(i)
    img = Image.open(loc)
    img.load()
    photoimg = ImageTk.PhotoImage(img)
    photoimg.append(photoimage_list) # Add it to a list so it isn't garbage collected!!
    window = tk.Toplevel()
    window.geometry("200x200")
    tk.Label(window, text="this is window %s" % i).pack()
    tk.Label(window, image=photoimg).pack()

root.mainloop()

只需確保不對photoimage_list列表進行垃圾收集,所以就不要刪除該列表,也不要丟失所有強引用。

您可以在https://rushter.com/blog/python-garbage-collector/上了解有關垃圾回收的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM