How to center the Tkinter label
Tkinter is Python's GUI module that comes with the Python standard library. It is used to create cross-platform desktop GUI applications. It's a lightweight and is easy to use to create GUI applications, as compared to other modules available in Python. In this answer, we'll learn how to center the Tkinter label widget.
Syntax
label.place(relx=0.5, rely=0.5, anchor=CENTER)
Code example
# Import the Tkinter library
from tkinter import *
# Create an instance of Tkinter window
window = Tk()
# Set the size of the window
window.geometry("300x300")
# Create a label widget
label = Label(window, text = "Hello from Educative !!!")
# Center the label widget
label.place(relx = 0.5, rely = 0.5, anchor = CENTER)
window.mainloop()Note: The above program runs on the Tkinter version
8.6.
Code explanation
In the above code snippet, we have the following steps:
Line 5: We create an instance of Tkinter class
Tk()and assign it to the variablewindow.Line 8: We set the window size as
300x300pixels.Line 11: We create a label using the
Label()widget.Line 14: We place the label at the center of the window by specifying the center position of the window using
relx = 0.5andrely = 0.5as parameters and passingCENTERas a value to theanchorparameter.
Free Resources