Why justify and anchor do not work for Label of Python Tkinter

12,586

This is because you haven't set width for Label, if you don't set it, Label will fit its content. So in short, the text inside Label is worked with anchor option, but Label's length is the same as text's length. And what located at center is not text but Label.

If you manually set a width for it:

Label(root, text=llist[i], anchor="e", width=20).grid(row=nrow, column=0)

It will work, but it is difficult to manually specify the length of Label, so use grid's sticky option is much better.

Share:
12,586
rnso
Author by

rnso

.

Updated on June 04, 2022

Comments

  • rnso
    rnso over 1 year

    I am using following code and trying to center the text on labels:

    from tkinter import * 
    root = Tk()
    llist = ["first:","second label:","a really long label:","fourth:","fifth:"]
    nrow = 0
    for i in range(len(llist)):
        # Label(root, text=llist[i], justify='right').grid(row=nrow, column=0) # does not work
        # Label(root, text=llist[i], justify=RIGHT).grid(row=nrow, column=0) # does not work
        # Label(root, text=llist[i], anchor=E).grid(row=nrow, column=0) # does not work
        # Label(root, text=llist[i], anchor=E, justify=RIGHT).grid(row=nrow, column=0) # does not work
        Label(root, text=llist[i]).grid(row=nrow, column=0, sticky=E) # WORKS; 
        Entry(root).grid(row=nrow, column=1)
        nrow += 1
    root.mainloop()
    

    The text remains in center with options that I mention as not working in above code:

    enter image description here

    Only with sticky option in the grid() it works properly:

    enter image description here

    Why justify and anchor options of Label do not work in above code, even though they are mentioned at several places such as http://effbot.org/tkinterbook/label.htm ? How can justify and anchor be used to align text in Labels?

  • Russell Smith
    Russell Smith over 5 years
    What does "it is difficult to manually specify the length of Label" mean? Why is it difficult?
  • Sraw
    Sraw over 5 years
    @BryanOakley Because in most of complicated cases, you cannot decide width easily. In this simple case, surely you can set width to max([len(text) for text in llist])