Tkinter:为所有帧添加图像作为背景

2024-10-02 14:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在创建Tkinter应用程序时遇到一些问题。我有很多类(创建一个复杂的应用程序),希望在任何地方都使用相同的图像作为背景。我不知道怎么做。我想它一定来自我的父母框架?有人能帮我解决这个问题吗

import tkinter as tk
import tkinter.messagebox as tm
from tkinter import *

LARGE_FONT = ("Courier", 12)

Background = ('#e6eeff')


class MyApp(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 (UserLogin, MainMenu, TestPage, signupPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(UserLogin)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.configure(background='#e6eeff')
        frame.tkraise()

#I have a few more classes after this point (all representing different pages)

if __name__ == '__main__':

    app = MyApp()
    app.geometry('1280x720')
    app.title('MyApp(alpha 1.0)')
    app.mainloop()

Tags: importselfapp应用程序framestkintercontainerdef
1条回答
网友
1楼 · 发布于 2024-10-02 14:22:18

最简单的解决方案是在MyApp中创建一次映像,并让每个帧通过控制器引用映像

class MyApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.background_image = tk.PhotoImage("the_image.gif")
        ...

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        background = tk.Label(self, image=controller.background_image)
        background.place(relx=.5, rely=.5)
        ...

相关问题 更多 >