I have a tkinter window I'd like to place in the middle of the screen, and am using Python 3 code like this:
import tkinter as tk
window = tk.Tk()
window_width = 500
window_height = 400
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
horiz_centre = int((screen_width - window_width) / 2)
vert_centre = int((screen_height - window_height) / 2)
window.geometry(f"{window_width}x{window_height} {horiz_centre} {vert_centre}")
window.mainloop()
My window appears on the screen towards the top left, rather than centered as I'd like and expect from this code. My variables have the values I expect.
Running the same code multiple times does not guarantee the window will appear in the same location each time.
What's going on here?
Thank you.
CodePudding user response:
Your code works perfectly fine for me. It shows up in the middle of the screen every time I run the script - So that's the good news.
As far as why it's not working for you, I wonder if it could be the issue @jasonharper had stated in the comments. Otherwise I have had other issues that are similar with dual monitors and resolution settings that are worth a quick check.
Give this a try:
1.) Right-click your desktop and select "Display settings"
2.) Ensure your scale and layout are set to the recommended resolutions.
3.) Disconnect any additional monitors you may have connected.
