【问题标题】:Cannot set a background color for my tkinter application?无法为我的 tkinter 应用程序设置背景颜色?
【发布时间】:2021-03-15 21:42:46
【问题描述】:

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

可运行代码:

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

【问题讨论】:

  • 你试过<any tkinter widget>.config(background="black")
  • @TheLizzard 是的,正如预期的那样,它会导致相同的结果

标签: python python-3.x tkinter tkinter-layout


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!我对这个错误完全视而不见,根源在于习惯......
猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 2012-06-04
  • 2014-03-29
  • 2013-01-07
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
相关资源
最近更新 更多