Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to place objects in the middle of a frame using tkinter?
To place objects in the middle of a frame in tkinter, we can use the place() method with relative positioning. This approach ensures widgets remain centered even when the window is resized.
Syntax
The basic syntax for centering widgets using place() ?
widget.place(relx=0.5, rely=0.5, anchor=CENTER)
Parameters
relx=0.5 − Places widget at 50% of parent's width
rely=0.5 − Places widget at 50% of parent's height
anchor=CENTER − Uses widget's center as reference point
Example
Here's how to center a button in a tkinter window ?
# Import the Tkinter library
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter frame
win = Tk()
# Define the geometry
win.geometry("750x350")
win.title("Centered Widget Example")
# Create Buttons in the frame
button = ttk.Button(win, text="Button at the Center")
button.place(relx=0.5, rely=0.5, anchor=CENTER)
win.mainloop()
Centering Multiple Widgets
You can center multiple widgets by adjusting their relative positions ?
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("600x400")
win.title("Multiple Centered Widgets")
# Center a label above the button
label = ttk.Label(win, text="Centered Label")
label.place(relx=0.5, rely=0.4, anchor=CENTER)
# Center the button
button = ttk.Button(win, text="Centered Button")
button.place(relx=0.5, rely=0.6, anchor=CENTER)
win.mainloop()
Key Points
Relative positioning (0.0 to 1.0) makes widgets responsive to window resizing
The
CENTERanchor ensures the widget's center aligns with the specified positionWithout
anchor=CENTER, the widget's top-left corner would be positioned at the centerThis method works with all tkinter widgets (Button, Label, Entry, etc.)
Conclusion
Use place(relx=0.5, rely=0.5, anchor=CENTER) to center widgets in tkinter. This approach creates responsive layouts that maintain centering when the window is resized.
