[英]Tkinter - can't open multiple photos at the same time (Python)
im trying to open multiple photos at the same time in 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()
It opens 5 windows as needed (not including root window), but the pictures doesn't show up. 它会根据需要打开5个窗口(不包括根窗口),但图片不会显示。 Suggestions?
建议? Thnx in advance
提前Thnx
You need to add a label with the argument image=photoimg
onto the window for the image to show up. 您需要在窗口上添加带有参数
image=photoimg
的标签,以显示图像。
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. 像乔纳·弗莱明(Jonah Fleming)所说的那样,添加
image=photoimg
,您必须保留对每个PhotoImage的引用,否则当将photoimg
变量分配给另一个PhotoImage时, photoimg
它们进行垃圾回收。 The simplest way to bypass this problem is to keep the PhotoImage instances in a list. 绕过此问题的最简单方法是将PhotoImage实例保留在列表中。 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. 只需确保不对
photoimage_list
列表进行垃圾收集,所以就不要删除该列表,也不要丢失所有强引用。
You can read more about garbage collection at https://rushter.com/blog/python-garbage-collector/ . 您可以在https://rushter.com/blog/python-garbage-collector/上了解有关垃圾回收的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.