简体   繁体   中英

tkinter label does not justify properly

I am trying to get a label to be center justified between a given width, but it's not working. What am I doing wrong?

from tkinter import *
from tkinter.ttk import *

def main():
    root = Tk()
    root.geometry("200x100")
    root.minsize(0,0)
    root.resizable(0,0)
    a = Label(master=root, text="Hello World", justify="center", background="red")
    a.pack()
    a.place(x=0,y=0, width=120)
    mainloop()
main()

The text is properly justified in the label. The problem is that you didn't tell the label to stretch to fill the window. To do that, pack it like this:

a.pack(fill="x")

Also, it serves no purpose to call pack and then immediately call place -- only the last one will have any effect. Plus, you should avoid using place unless you have no other choice. Place is fine, but it makes your program harder to maintain, and harder to get it to grow and shrink.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM