【问题标题】:How to change background image for each Page如何更改每个页面的背景图像
【发布时间】:2019-02-09 17:58:15
【问题描述】:

是的,我确实知道如何配置背景图像,但是在这种情况下,我不知道作为小部件的父级引用什么,因为当我使用 self.

对于代码示例,我将使用来自 Bryan Oakleys 切换框架代码的样板:

import tkinter as tk                
from tkinter import font  as tkfont 


class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        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):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

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

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        **### Here for example this does nto do anything to the window**

        self.background_image= tk.PhotoImage("image_path")
        self.background_label = tk.Label(self, image=self.background_image)
        self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
        self.background_label.image = self.background_image


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

提前感谢您的帮助!

【问题讨论】:

  • , relwidth=1, relheight=1 ?那很小....除此之外...这些是局部变量,一旦您离开__init__就会消失...也许您可以使用self.background_label让它们停留更长时间?如果我是 python 解释器,我可能会销毁这些变量 - 它们不再需要
  • 哦,对不起,我从另一个帖子中提取了该代码,但尽管仍然没有图像出现
  • 您需要保留对图像的引用。在放置方法后添加 background_label.img = background_image
  • @HenryYik 我也试过了,还是没有图片
  • @PatrickArtner:relwidth 为 1 并不小。相对宽度介于 0 和 1 之间,因此 1 实际上意味着它与其容器一样宽。

标签: python-3.x tkinter


【解决方案1】:

我刚刚注意到您的 PhotoImage 语法也是错误的。你可以阅读它here。

self.background_image= tk.PhotoImage("image_path")

应该是:

self.background_image= tk.PhotoImage(file="image_path")

同时添加self.background_label.img = self.background_image,然后一切就绪。

【讨论】:

  • 啊,基本上我缺少的是自我引用,我只是忘记了文件参数,因为我从我的主应用程序中提取它只是为了为这个问题制作一个示例
猜你喜欢
  • 2020-08-23
  • 2011-09-07
  • 2013-02-02
  • 2021-03-27
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多