How to center a label in a frame of fixed size in Tkinter?

TkinterPythonGUI-Programming

Tkinter is a GUI toolkit in Python used to build desktopbased applications. Tkinter provides several widget functionalities and class libraries to develop various components of an application. The Frame widget is one of the widgets that works similar to the standard tkinter default window. You can place as many widgets as you want in a Frame widget. You can also customize the properties like resizing the frame, its background color and also the layout using geometry managers.

Example

Suppose we need to create an application in which we want to create a Label widget inside a fixedsize frame. The Label widget must be placed at the center and to achieve this, we can use the anchor=CENTER property of the place geometry manager. The following example demonstrates how to implement it.

# Import the library
from tkinter import *
from tkinter import filedialog

# Create an instance of window
win=Tk()

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

# Create a frame widget
frame=Frame(win, width=300, height=300)
frame.grid(row=0, column=0, sticky="NW")

# Create a label widget
label=Label(win, text="I am inside a Frame", font='Arial 17 bold')
label.place(relx=0.5, rely=0.5, anchor=CENTER)

win.mainloop()

Output

Running the above code will display a window with a centered Label widget inside a Frame.

raja
Published on 22-Dec-2021 11:02:47
Advertisements