无法为我的 tkinter 应用程序设置背景颜色?

Cannot set a background color for my tkinter application?

当我尝试为我的主框架设置背景颜色时,所有小部件都是子框架,它只会改变背景的最底部。如果我为所有 Frame 小部件设置背景,它仍然不会为一些空白 space 着色。如何为其设置背景颜色?这是带有彩色框架的结果。

可运行代码:

import tkinter as tk


class ToolbarButton(tk.Button):

    def __init__(self, master, text, pixelref, *args, **kw):
        super().__init__(master)
        self.configure(text=text, image=pixelref, height=20, width=20, compound='center')


class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs, bg="red")
        self.parent = parent

        # Textframe
        self.text_frame = tk.Frame(root, width=600, height=790, bg="green") #doesn't show: has text_widget over
        self.text_frame.pack_propagate(False)
        self.text_widget = tk.Text(self.text_frame, width=1, height=1)
        self.text_widget.pack(expand=True, fill='both')

        # Toolbar
        self.toolbar = tk.Frame(root,bg="blue")
        self.pixel = tk.PhotoImage(width=1, height=1)

        self.bold_button = ToolbarButton(self.toolbar, 'B', self.pixel)
        self.bold_button.pack(side='left', padx=4)
        self.italic_button = ToolbarButton(self.toolbar, 'I', self.pixel)
        self.italic_button.pack(side='left', padx=4)
        self.underline_button = ToolbarButton(self.toolbar, 'U', self.pixel)
        self.underline_button.pack(side='left', padx=4)

        # Packing
        self.toolbar.pack(side='top', pady=60)
        self.text_frame.pack(expand=True)


if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

您已将 text_frame 小部件放置在根目录中,而不是应用程序框架中。我想你想要 self 而不是 root。这使它的行为符合我的预期。

    self.text_frame = tk.Frame(self, width=600, height=790, bg="green") #doesn't show: has text_widget over