Python missing image

你。 提交于 2020-02-05 13:06:13

问题


So I want to create a window with a displayed image (from a specific file) and single button to close the window. So far it shows the window, resizes the window to fit the the image, but doesn't show the image itself. Here's what I have so far

from Tkinter import *
import Image
import ImageTk
class MyApp:                         
  def __init__(self, rData):
    self.cont1 = Frame(rData)
    self.cont1.pack(side="top", padx=5, pady=5)    
    self.button1 = Button(rData) 
    self.button1["text"]= "Exit"     
    self.button1["background"] = "red"      
    self.button1.pack(side="bottom",padx=5, pady=5, fill=X)                         
    self.button1["command"]= rData.destroy
    self.picture1 = Label(self.cont1)
    self.picture1["image"] = ImageTk.PhotoImage(Image.open("fire.ppm"))
    self.picture1.pack(fill="both")  
root = Tk()
myapp = MyApp(root)  
root.mainloop()

When I wrote the same thing without making it into a class, it worked just fine.


回答1:


The problem is that you need to keep your own reference to the PhotoImage you create, or python will garbage collect it, because Tkinter doesn't keep a reference to it. This is either a bug or a feature, depending on your thinking. This code should solve your problem:

from Tkinter import *
import Image
import ImageTk
class MyApp:                         
  def __init__(self, rData):
    self.cont1 = Frame(rData)
    self.cont1.pack(side="top", padx=5, pady=5)    
    self.button1 = Button(rData) 
    self.button1["text"]= "Exit"     
    self.button1["background"] = "red"      
    self.button1.pack(side="bottom",padx=5, pady=5, fill=X)                         
    self.button1["command"]= rData.destroy
    self.picture1 = Label(self.cont1)
    self.photoImage = ImageTk.PhotoImage(Image.open("fire.ppm"))   # This line prevents your photo image from getting garbage collected.
    self.picture1["image"] = self.photoImage
    self.picture1.pack(fill="both")  
root = Tk()
myapp = MyApp(root)  
root.mainloop()


来源:https://stackoverflow.com/questions/17436741/python-missing-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!