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

时间:2019-10-07 21:17:44

标签: python python-3.x tkinter

我正在创建的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()

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是在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)
        ...