在Tkinter中更改多个窗口的背景

时间:2015-02-15 17:54:35

标签: python user-interface background tkinter

我正在尝试在程序中创建一个设置菜单,以便您可以更改程序中所有窗口的背景。但我不知道如何制作它,所以单击按钮时,背景会发生变化。有帮助吗?如果需要,这是我到目前为止所拥有的:

    #Settings
    class programSettings(tk.Frame):

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

            #Setups
            title = ttk.Label(self, text = "Settings", font = LARGE_FONT)

            colorButton = ttk.Button(self, text = "Background Color", command = lambda: controller.show_frame(color))
            menuButton = ttk.Button(self, text = "Main Menu", command = lambda: controller.show_frame(StartPage))

            #Placement
            title.pack()
            colorButton.pack()
            menuButton.pack()

    #Color
    class color(tk.Frame):

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

            #Setups
            blueButton = ttk.Button(self, text = "Blue", command = lambda: controller.show_frame(programSettings))
            blueButton.configure(bg = "#4285F4")
            #Placement
            blueButton.pack()

它并不多,我尝试了一些东西,但它们没有用。

1 个答案:

答案 0 :(得分:1)

有两种解决方案:保留对每个窗口的引用并使用configure方法更改背景,或创建一个在更改某些全局值后重新创建整个UI的函数。

这里概述了你如何做第一种方法:

class ControllerClass(object):
    def __init__(self):
        ...
        self.windows = []
        ...
    def show_frame(self, frame_class):
        ...
        the_frame = frame_class(root, self)
        self.windows.append(the_frame)
        ...
    def change_color(self):
        ...
        for frame in self.windows:
            frame.configure(background=the_color)
        ...

当然,它应该比这复杂一点。例如,您的控制器可能具有"设置"字典而不是单一颜色。此外,您可能会考虑让每个窗口对象负责更改自己的颜色,因此您可能会frame.set_color(the_color)。这样,每个窗口不仅可以设置自身的背景,还可以设置任何相关的子窗口。