微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

enter image description here

可运行代码

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,**kwargs):
        tk.Frame.__init__(self,**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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。