Hamish
Hamish

Reputation: 513

PYTHON: How to anchor two labels to top using tkinter

import tkinter as tk

root = tk.Tk()
root.title("window")

yellow_header = tk.Label(root, text = 'Header', bg = 'light yellow')
yellow_header.pack(side = tk.TOP, anchor = tk.N, expand = 1, fill = tk.X)

yellow_header2 = tk.Label(root, text = 'paragraph', bg = 'light yellow')
yellow_header2.pack(side = tk.TOP, anchor = tk.N, expand = 1, fill = tk.X)

root.mainloop()

For the above code I am trying to have both these labels anchored to the top and directly below one another. Although the first label (yellow_header) anchors to the top, where as the second label (yellow_header2) when expanded move towards the centre. How can I fix this?

Thank you in advance!

Upvotes: 2

Views: 1259

Answers (2)

fhdrsdg
fhdrsdg

Reputation: 10552

Don't use expand=1. From effbot:

The expand option tells the manager to assign additional space to the widget box. If the parent widget is made larger than necessary to hold all packed widgets, any exceeding space will be distributed among all widgets that have the expand option set to a non-zero value.

With expand=1, when you make the window larger, the space is distributed between the two labels. So even though you only tell them to fill it in the X direction, they are given the space in both directions. The second label is placed directly under the space that is available to the first label, which is half of the window.

I've tried to explain and visualize the difference between expand and fill in this answer.

P.S. You don't need anchor=tk.N either. When the space available to the widget and the size of the widget are the same, the anchor option makes no difference. Also, side=tk.TOP is the default so you could decide to omit that too, leaving you with only fill=tk.X.

Upvotes: 2

Silverfibre
Silverfibre

Reputation: 41

Looking at the docs I see:

The Text widget is used to display text in multiple lines.

and this seems to work:

import tkinter as tk

root = tk.Tk()
root.title("window")

yellow_header = tk.Label(root, text = 'Header\nParagraph', bg = 'light yellow')
yellow_header.pack(side = tk.TOP, anchor = tk.N, expand = 1, fill = tk.X)

That might be a bit OS specific and perhaps the proper way would be:

import os
...
yellow_header = tk.Label(root, text = 'Header' + os.linesep + 'Paragraph', bg = 'light yellow')

When increasing the length of the first string the second still remains in the center.

Upvotes: 2

Related Questions