tkinter windows appear at the center of the screen in python

You can center a Tkinter window by calculating the screen's center coordinates and setting the window to appear there using the geometry method. Here's an example:

main.py
import tkinter as tk

# Create the window
window = tk.Tk()

# Set the window's size
window.geometry("300x200")

# Calculate the center of the screen
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
center_x = int(screen_width / 2 - 150) # Half the window's width
center_y = int(screen_height / 2 - 100) # Half the window's height

# Set the window to appear at the center of the screen
window.geometry(f"+{center_x}+{center_y}")

# Run the GUI loop
window.mainloop()
504 chars
20 lines

In this example, we first create the window using tk.Tk(), then set its size to 300x200 using geometry. Next, we calculate the center coordinates of the screen using winfo_screenwidth and winfo_screenheight, and divide the values by 2 to get the midpoint of the screen. We then subtract half the window's height and width from the midpoint to get the top-left corner of the window. Finally, we use the geometry method again to set the window to appear at this location, using the +x+y syntax to specify the offset from the top-left corner of the screen.

Running this code will display a window that is centered on the screen.

gistlibby LogSnag