Skip to content Skip to sidebar Skip to footer

Setting Background Color Of A Tkinter Ttk Frame

I want to simply set a background color to the frame within the tkinter window. The background color for the window was successfully set, but not for the frame inside. Simply ente

Solution 1:

When using ttk widgets, all styling should be done using ttk.Style.

You need to initialize the style class with s = ttk.Style(), and can then change attributes of the different widget styles with s.configure('StyleName', option='value')

You can find the default style names here. So for a Frame the style name is TFrame. When you configure an option for this style, it will be used by all frames. When you want to configure an option for a single frame, you can create a new style based on the original style by using a name of the form newName.oldName. In your case, this could be Frame1.TFrame. You can then tell a frame to use this style by passing style='Frame1.TFrame'.

If you use the following in your code, you will see that the first frame is red, the second is blue and all other frames are green:

# Initialize style
s = ttk.Style()
# Create style used by default for all Frames
s.configure('TFrame', background='green')

# Create style for the first frame
s.configure('Frame1.TFrame', background='red')
# Use created style in this frame
tab1 = ttk.Frame(mainframe, style='Frame1.TFrame')
mainframe.add(tab1, text="Tab1")

# Create separate style for the second frame
s.configure('Frame2.TFrame', background='blue')
# Use created style in this frame
tab2 = ttk.Frame(mainframe, style='Frame2.TFrame')
mainframe.add(tab2, text="Tab2")

Solution 2:

You are using ttk widgets which have their styling options wraped up in styles. Thus, for ttk widgets you cannot change such style options as bgcolor directly. You have to edit or create new styles. More info about this here: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-style-layer.html

Change your code like this to display a new color:

# create frame style
s = ttk.Style()
s.configure('new.TFrame', background='#7AC5CD')

#create tabs within the frame
tab1 = ttk.Frame(mainframe, style='new.TFrame')
mainframe.add(tab1, text="Tab1")


tab2 = ttk.Frame(mainframe, style='new.TFrame')
mainframe.add(tab2, text="Tab2")


tab3 = ttk.Frame(mainframe, style='new.TFrame')
mainframe.add(tab3, text="Tab3")

tab4 = ttk.Frame(mainframe, style='new.TFrame')
mainframe.add(tab4, text="Tab4")

tab5 = ttk.Frame(mainframe, style='new.TFrame')
mainframe.add(tab5, text="Tab4")

Solution 3:

Please follow below step

  1. Create object of style class

    s = ttk.Style()

  2. Using that object define style

  3. First argument : style name, this name is placed in all frames where you want to give this style

    s.configure('frameName', background='#fff')

  4. Create frame and assign this style

    frm1 = ttk.Frame(root, style='frameName')

Post a Comment for "Setting Background Color Of A Tkinter Ttk Frame"