@@ -924,23 +924,41 @@ def geometry_offset(value):
924924 return f'+{ value } ' if value >= 0 else str (value )
925925
926926def center_main_window_macos (window , width , height ):
927+ """
928+ MacOS: Determine full desktop dimensions and which monitor the mouse is on,
929+ then center the window within those specific monitor boundaries.
930+ """
931+ window .update_idletasks ()
932+ mx , my = window .winfo_pointerxy ()
933+
934+ # 1. Get primary monitor dimensions (always starts at 0,0 on macOS)
935+ window .geometry ("+0+0" )
927936 window .update_idletasks ()
928- mouse_x , mouse_y = window .winfo_pointerxy ()
929- # Moving the window lets Tk report the screen containing the pointer on
930- # macOS, where its screen dimensions are monitor-specific.
931- window .geometry (f'{ geometry_offset (mouse_x )} { geometry_offset (mouse_y )} ' )
937+ pw = window .winfo_screenwidth ()
938+ ph = window .winfo_screenheight ()
939+
940+ # 2. Move to mouse position to get the second monitor's dimensions
941+ window .geometry (f'{ geometry_offset (mx )} { geometry_offset (my )} ' )
932942 window .update_idletasks ()
933- screen_width = window .winfo_screenwidth ()
934- screen_height = window .winfo_screenheight ()
935- left = (mouse_x // screen_width ) * screen_width
936- top = (mouse_y // screen_height ) * screen_height
937- right = left + screen_width
938- bottom = top + screen_height
939-
940- start_x = left + max (0 , (right - left - width ) // 2 )
941- start_y = top + max (0 , (bottom - top - height ) // 2 )
942- window .geometry (
943- f'{ width } x{ height } { geometry_offset (start_x )} { geometry_offset (start_y )} ' )
943+ sw = window .winfo_screenwidth ()
944+ sh = window .winfo_screenheight ()
945+
946+ # 3. Get virtual desktop bounds to handle monitors to the left/right
947+ vx = window .winfo_vrootx ()
948+
949+ # 4. Determine the actual boundaries of the monitor the mouse is on
950+ if mx < 0 : # Monitor is to the left of primary
951+ mon_x , mon_y , mon_w , mon_h = vx , 0 , abs (vx ), sh
952+ elif mx >= pw : # Monitor is to the right of primary
953+ mon_x , mon_y , mon_w , mon_h = pw , 0 , sw , sh
954+ else : # Mouse is on the primary monitor
955+ mon_x , mon_y , mon_w , mon_h = 0 , 0 , pw , ph
956+
957+ # 5. Center the window within those specific monitor boundaries
958+ start_x = mon_x + (mon_w - width ) // 2
959+ start_y = mon_y + (mon_h - height ) // 2
960+
961+ window .geometry (f'{ width } x{ height } { geometry_offset (start_x )} { geometry_offset (start_y )} ' )
944962
945963main_window .attributes ('-topmost' , True )
946964main_window .focus_force ()
0 commit comments