简体   繁体   中英

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

im trying to open multiple photos at the same time in 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()

It opens 5 windows as needed (not including root window), but the pictures doesn't show up. Suggestions? Thnx in advance

You need to add a label with the argument image=photoimg onto the window for the image to show up.

Your code:

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()

Along with adding image=photoimg like Jonah Fleming said, you have to keep a reference to each PhotoImage, or they will be garbage collected when the photoimg variable is assigned to another PhotoImage. The simplest way to bypass this problem is to keep the PhotoImage instances in a list. That would be done like this:

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()

Just make sure that the photoimage_list list doesn't get garbage collected, so don't have the list ever be deleted/lose all of its strong references.

You can read more about garbage collection at https://rushter.com/blog/python-garbage-collector/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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