Search code examples
pythontkinter

How to apply the color of a styled `Labelframe` to its label text also


The following code:

from tkinter import *
from tkinter.ttk import *
root = Tk()
root['bg'] = 'yellow'
root.title("Styled Labelframe")
root.geometry("250x150")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
Style().configure('my.TLabelframe', background='red')
frame = Labelframe(root, style='my.TLabelframe', text=" Testing styled Labelframe... ")
frame.grid(column=0, row=0, sticky=(N,W,E,S), padx=20, pady=20)
root.mainloop()

displays this:

enter image description here

I want the text of the Labelframe to have the same background color (red) as the rest of the Labelframe. I also want to center it, instead of aligning to left.

How can I accomplish this?

Since I am a beginner, any other comments on my coding are welcome also.


Solution

  • You're looking for TLabelframe.Label for styling the label, and the labelanchor param for specifying the label's position. There's good info on that second point available here.

    from tkinter import *
    from tkinter.ttk import *
    root = Tk()
    root['bg'] = 'yellow'
    root.title("Styled Labelframe")
    root.geometry("250x150")
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    style = Style()
    # this updates the frame background
    style.configure('my.TLabelframe', background='red')
    # and this will update the label text background
    style.configure('my.TLabelframe.Label', background='red')
    # specify the labelanchor here to set the label's alignment/position
    frame = Labelframe(root, style='my.TLabelframe', text=" Testing styled Labelframe... ", labelanchor='n')
    frame.grid(column=0, row=0, sticky=(N,W,E,S), padx=20, pady=20)
    root.mainloop()
    

    Unrelated, but since you asked for comments:

    sticky will take string arguments, so you can just use sticky='nsew' or whatever - order doesn't matter, as far as I've seen.

    Also, it's generally advisable to avoid star imports, e.g. from foo import *, because they can lead to issues (see here).

    Instead, you'll typically want to use:

    import tkinter as tk
    from tkinter import ttk
    

    If you do it this way, you just need to prefix your widgets (and any other tkinter classes) with the appropriate namespace tk or ttk like this:

    root = tk.Tk()
    ...
    style = ttk.Style()
    ...
    frame = ttk.LabelFrame()
    # etc.