使用tkinter仅在其自己的帧中显示图像

时间:2018-12-18 14:26:33

标签: python tkinter

我正在尝试使用tkinter创建带有按钮和图像的简单GUI。我有一个带有图像和按钮的首页,可以将您带到其他页面(框架)。问题是我的起始页中的图像仍然存在,并显示在其他框架中。

代码:

import tkinter as tk

LARGE_FONT = ("Verdana", 12)


class SeaofBTCapp(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, PageTwo):
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.geometry("800x480")
        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)
        label = tk.Label(self, text="Start Page", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        #canvas1 = tk.Canvas(width=600, height=300, bg="gray")
        #self.img = tk.PhotoImage(file="mario.png")
        #canvas1.create_image(20, 20, image=self.img)
        #canvas1.pack()

        photo = tk.PhotoImage(file="mario.png")
        labelimg = tk.Label(image=photo)
        labelimg.image = photo  # keep a reference!
        labelimg.pack()

        button = tk.Button(self, text="Visit Page 1",
                           command=lambda: controller.show_frame(PageOne))
        button.pack()

        button2 = tk.Button(self, text="Visit Page 2",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        button1 = tk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        button1 = tk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page One",
                            command=lambda: controller.show_frame(PageOne))
        button2.pack()


app = SeaofBTCapp()
app.mainloop()

1 个答案:

答案 0 :(得分:1)

问题是您尚未指定labelimg的父级,因此默认情况下它是主窗口。因此,标签被包装在容器下方,因此始终可见。

更改

labelimg = tk.Label(image=photo)

进入

labelimg = tk.Label(self, image=photo)
在课程StartPage中的

应该可以解决您的问题。