Search code examples
python-3.xuser-interfacetkinterttk

Python3 GUI change frame background color


I am relatively new at python and I am building this GUI interface. The code represents something I got mostly online but have been able to edit for my own uses pretty successfully. Anyways, I want to full background to be a different color than just the gray. As you can see, I expanded the widget and can change the widget background color, but the main stuff is still gray.

I assume this means I need to change the Frame background color? Not shown in the code are my several attempts using .configure(), styles, etc to accomplish my goal. I was successful a few ways to make the background of the text portions a different color, but not the overall.

I assume I am missing something small in syntax and welcome any help getting it to work - thanks!

import tkinter
from tkinter import tt

class Adder(ttk.Frame):
    """The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def init_gui(self):
        """Builds GUI."""

        self.root.title('Number Adder')

        self.grid(column=0, row=0, sticky='nsew')

        self.num1_entry = ttk.Entry(self, width=5)
        self.num1_entry.grid(column=1, row = 2)

        ttk.Label(self, text='Number Adder').grid(column=0, row=0,
                columnspan=4)
        ttk.Label(self, text='Number one').grid(column=0, row=2,
                sticky='w')

        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

if __name__ == '__main__':
    root = tkinter.Tk()
    root.geometry('200x100')
    root.configure(background = 'blue')
    Adder(root)
    root.mainloop()

Solution

  • To set background color for a widget you first have to create a style. Then you have to configure the style background color and associate it with the type of widget you are using it on. Make theese three lines the last lines of your __init__() function:

    style = ttk.Style()     # Create style
    style.configure("Blue.TFrame", background="blue") # Set bg color
    self.config(style='Blue.TFrame')    # Apply style to widget
    

    The name has to end with a section that identifies the type of widget, in this case a Frame => "TFrame". Blue is the name I gave it to separate if from other frame styles I might have. If you just want the one style you can call it "TFrame".

    Have a look at TkDocs:Styles and Themes