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
Selected Reading
How to specify where a Tkinter window should open?
Tkinter allows you to control where a window appears on screen using the geometry() method. The geometry method accepts a string format: "widthxheight+x_offset+y_offset" to set both size and position.
Syntax
window.geometry("widthxheight+x_offset+y_offset")
Where:
- width, height − Window dimensions in pixels
- x_offset, y_offset − Position from top-left corner of screen
Example
Here's how to create a window that opens at position (300, 300) ?
# Import the required libraries
from tkinter import *
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x350+300+300")
# Create a Label
Label(win, text="This Window Opens at (300,300)", font=('Helvetica', 15, 'bold')).pack(pady=30)
win.mainloop()
Centering a Window
You can center a window on the screen by calculating screen dimensions ?
from tkinter import *
win = Tk()
# Get screen dimensions
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()
# Calculate center position
window_width = 600
window_height = 400
x = (screen_width // 2) - (window_width // 2)
y = (screen_height // 2) - (window_height // 2)
# Set geometry to center the window
win.geometry(f"{window_width}x{window_height}+{x}+{y}")
Label(win, text="Centered Window", font=('Helvetica', 15, 'bold')).pack(pady=30)
win.mainloop()
Different Position Examples
| Position | Geometry String | Description |
|---|---|---|
| Top-left corner | "600x400+0+0" |
Window starts at screen origin |
| Top-right corner | "600x400+{screen_width-600}+0" |
Aligned to right edge |
| Custom position | "600x400+300+150" |
300px from left, 150px from top |
Conclusion
Use geometry("widthxheight+x+y") to specify window size and position. Calculate screen dimensions with winfo_screenwidth() and winfo_screenheight() for dynamic positioning.
Advertisements
