class 中的 Tkinter PhotoImage 不会显示
Tkinter PhotoImage in a class won't show
我有一个按钮可以显示带有图片标签的新框架。标签和图像与所有教程中的完全一样,但图片不显示。它是一个 .gif。我究竟做错了什么?
这是我的代码:
from Tkinter import *
class Main(object):
def __init__(self, root):
self.f1=Frame(root)
self.f1.grid()
b1=Button(f1, command=self.photo, text="Picture")
b1.grid()
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image=self.img1
self.l3.grid()
root=Tk()
app=Main(root)
root.mainloop()
默认的第一个参数是图像的名称。如果你给它一个文件路径,你需要在路径前面指定 file=
以便 PhotoImage 知道它是文件的路径而不是图像的名称。
self.img1=PhotoImage(file="CO2_Levels.gif")
我知道这是一个老问题。但是如果有人 运行 遇到同样的问题,那是因为当你从函数中 return 时图像被垃圾收集了。为避免这种情况,您应该保留对图像对象的引用。你的拍照方法,
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image = self.img1 # Reference to the image object
self.l3.image=self.img1
self.l3.grid()
我有一个按钮可以显示带有图片标签的新框架。标签和图像与所有教程中的完全一样,但图片不显示。它是一个 .gif。我究竟做错了什么? 这是我的代码:
from Tkinter import *
class Main(object):
def __init__(self, root):
self.f1=Frame(root)
self.f1.grid()
b1=Button(f1, command=self.photo, text="Picture")
b1.grid()
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image=self.img1
self.l3.grid()
root=Tk()
app=Main(root)
root.mainloop()
默认的第一个参数是图像的名称。如果你给它一个文件路径,你需要在路径前面指定 file=
以便 PhotoImage 知道它是文件的路径而不是图像的名称。
self.img1=PhotoImage(file="CO2_Levels.gif")
我知道这是一个老问题。但是如果有人 运行 遇到同样的问题,那是因为当你从函数中 return 时图像被垃圾收集了。为避免这种情况,您应该保留对图像对象的引用。你的拍照方法,
def photo(self):
self.f1.destroy()
self.f2=Frame(root)
self.f2.grid()
self.img1=PhotoImage("CO2_Levels.gif")
self.l3=Label(self.f2, image=self.img1)
self.l3.image = self.img1 # Reference to the image object
self.l3.image=self.img1
self.l3.grid()