代码之家  ›  专栏  ›  技术社区  ›  Moller Rodrigues

如何更改每页的背景图像

  •  0
  • Moller Rodrigues  · 技术社区  · 6 年前

    是的,我知道如何配置背景图像,但是在这种情况下,我不知道作为小部件的父级引用什么,因为当我使用self时没有显示任何内容。

    例如,我将使用Bryan Oakley的锅炉板切换帧代码:

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

    提前感谢您的帮助!

    1 回复  |  直到 6 年前
        1
  •  2
  •   Henry Yik    6 年前

    我刚注意到你的photoimage语法也是错误的。你可以读出来 here .

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

    应该是:

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

    还添加 self.background_label.img = self.background_image 然后你们都准备好了。