Search code examples
pythontkinterttkttkwidgets

Why is a ttk LabelFrame not showing the labelanchor I defined in a style?


I am trying to define the position of the label for a LabelFrame in a custom style in ttk. The label is, however, always showing on top of the frame no matter what I set "labelanchor" to. Am I missing something? Here's my code:

import tkinter as tk
from tkinter import ttk

# Create a Tkinter window
root = tk.Tk()

# Create the LabelFrame style
style = ttk.Style(root)
style.theme_use("alt")
style.configure('s.TLabelframe', labelanchor='s')

# Create a Frame
frame = ttk.LabelFrame(root, text="LabelFrame with labelanchor=n", style="s.TLabelframe")
frame.pack(padx=10, pady=10)

# Create a Lable inside the Frame
label = ttk.Label(frame, text="Label")
label.pack(padx=10, pady=10)

# Run the Tkinter event loop
root.mainloop()

I tried the code I gave but I was getting the label on top of the frame, while expecting it to be below it.


Solution

  • labelanchor is not a supported style of ttk.LabelFrame, but it can be specified when creating ttk.LabelFrame:

    import tkinter as tk
    from tkinter import ttk
    
    # Create a Tkinter window
    root = tk.Tk()
    root.geometry("400x200")
    
    # Create a Frame
    frame = ttk.LabelFrame(root, text="LabelFrame with labelanchor=s", labelanchor="s")
    frame.pack(padx=10, pady=10, fill="both", expand=1)
    
    # Create a Lable inside the Frame
    label = ttk.Label(frame, text="Label")
    label.pack(padx=10, pady=10)
    
    # Run the Tkinter event loop
    root.mainloop()
    

    Result:

    enter image description here