Home > OS >  Why is this text not centered when I explicitly make it? (Tkinter)
Why is this text not centered when I explicitly make it? (Tkinter)

Time:01-02

I just need to center a ttk Label on the top of my window.

from tkinter import *
from tkinter.ttk import *

window = Tk()

Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!", justify="center").place(x=500, y=0)

window.geometry("1000x600")
window.mainloop()

This code yields this: Window I expected it to be centered

What's the correct way to center it?

CodePudding user response:

Change the number of the x axis accordingly.. Like,

Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!", justify="center").place(x=400, y=0)

Or

Just simply use pack manager instead.

Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!", justify="center").pack()

CodePudding user response:

You can use anchor='n' to anchor it to north.

Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!").place(x=500, y=0, anchor='n')

Also, you can use pack to anchor the text you want to center.

from tkinter import *
from tkinter.ttk import *

window = Tk()

label = Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!")
label.pack(anchor="center")

window.geometry("1000x600")
window.mainloop()

Although, I recommend using grid to align your objects to ease up any future items you intend to add. https://docs.python.org/3/library/tkinter.html

CodePudding user response:

Easier way without using anchor. Just add resizable. Don't used place(). It is better to used pack().

from tkinter import *
from tkinter.ttk import *

window = Tk()
window.resizable(True, True)

Label(master=window, text="Welcome to the funny quiz!!!!!!!!!!!", justify="center").pack(side = TOP, pady = 10)

window.geometry("1000x600")
window.mainloop()
  • Related