我是tkinter的新手。我已经搜索了如何显示图像,并且一直在使用这种方法。据我了解,显示图像的原始方式是
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
homeimg = ImageTk.PhotoImage(Image.open('IMAGE_NAME'))
img = tk.Label(root, image=homeimg)
img.pack()
root.mainloop()
但是当我制作带有多帧的类并显示时,图像不会显示。
import tkinter as tk
from PIL import Image, ImageTk
class yep(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
homeimg = ImageTk.PhotoImage(Image.open('IMAGE_NAME'))
img = tk.Label(self, image=homeimg)
img.image = homeimg
img.pack()
# homeimg = ImageTk.PhotoImage(Image.open('IMAGE_NAME'))
# img = tk.Label(self, image=homeimg)
# img.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
app = yep()
app.mainloop()
带注释的代码是我尝试过的代码,但是没有用。
通过执行此代码,
img.image = homeimg
终于可以了。
如果您知道为什么,您可以解释一下吗?