Python缺失图像 [英] Python missing image

查看:348
本文介绍了Python缺失图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想创建一个带有显示图像(来自特定文件)的窗口和单击按钮来关闭窗口。
到目前为止,它显示窗口,调整窗口大小以适应图像,但不显示图像本身。
这里是我迄今为止

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

$ b

推荐答案

当我写同样的东西而不把它做成一个类时, >问题是你需要保留你自己引用的 PhotoImage 你创建,或者python会垃圾收集它,因为Tkinter不保存一个引用。这是一个错误或功能,这取决于你的想法。此代码应该解决您的问题:

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

这篇关于Python缺失图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆