How to center a Tkinter widget?

TkinterPythonGUI-Programming

Tkinter widgets are customizable by specifying their properties, for example, width, height, position, background color, etc. To position the Tkinters widgets, we can use place() geometry manager, where we will specify the anchor property. It can take (NW, N, NE, W, CENTER, E, SW, S, SE) as the position of the widget.

Example

In this example, we have forced a Label widget to the center of the window by specifying the anchor property.

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("700x350")

#Set the default color of the window
win.config(bg='#4fe3a5')

#Create a Label
Label(win, text = "Hello World!", font= ('Helvetica 25 bold')).place(relx=.5, rely=.5,anchor= CENTER)
win.mainloop()

Output

Running the above code will display a window with a Label widget at the center of the window.

raja
Published on 25-May-2021 09:03:56
Advertisements