0

I have multiple monitors, and when I try to center the window on the screen, it goes to the left edge of the screen. Code:

def center_window(window, window_width, window_height, offset_x=0, offset_y=0):
    s_width = window.winfo_screenwidth()
    s_height = window.winfo_screenheight()
    x_cordinate = int((s_width/2) - (window_width/2))
    y_cordinate = int((s_height/2) - (window_height/2))
    window.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate+offset_x, y_cordinate+offset_y))

If I disable a monitor, this doesn't happen, and the window gets centered correctly.

I tried other solutions, as explained in this question: How to center a window on the screen in Tkinter?

None of the answers work with a multiple-monitors setup. By the way I'm on Ubuntu22-04. Thanks for any help, I'll appreciate it.

citah9321
  • 1
  • 2

1 Answers1

0

Most commonly the Monitor with the upper left corner (0,0) is the primary screen. With that in mind, you can simply position your window with geometry('+0+0'), call update_idletasks() and then ask with winfo_screenwidth() for window's screen width and height and do the usual calculation.

Pro tipp: while you dont want to see a window flipping arround in your screen for the setup, you can use wm_attributes('-alpha') to make your actions invisible.

def center_window(window, window_width, window_height, offset_x=0, offset_y=0):
    window.wm_attributes('-alpha',0)#hide window
    window.geometry("{}x{}+{}+{}".format(window_width, window_height, 0,0) #0,0 primary Screen
    window.update_idletasks() #make sure the properties are updated

    s_width = window.winfo_screenwidth()
    s_height = window.winfo_screenheight()
    x_cordinate = int((s_width/2) - (window_width/2))
    y_cordinate = int((s_height/2) - (window_height/2))
    window.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate+offset_x, y_cordinate+offset_y))

    window.wm_attributes('-alpha',1)#show window
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • Would you be kind to edit my code and redefine the functions with this solution? – citah9321 Jun 24 '22 at 12:43
  • @citah9321 updated your code with the suggested changes. On success, consider to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235), else do let me know. – Thingamabobs Jun 24 '22 at 12:52
  • it still doesn't work, for some reason, the window is still on the left edge. – citah9321 Jun 24 '22 at 13:09
  • @citah9321 please provide a [mre]. I tested the code and it works as expected, after fixing the typo, for me. You may have another issue related in your code. – Thingamabobs Jun 24 '22 at 13:26