69 lines
2.6 KiB
Python
69 lines
2.6 KiB
Python
# LauncherTool/gui/utils_gui.py
|
|
"""
|
|
GUI utility functions.
|
|
"""
|
|
import tkinter as tk
|
|
|
|
class GuiUtils: # Rinominata da Utils a GuiUtils
|
|
"""
|
|
Utility class for generic GUI-related functions.
|
|
"""
|
|
|
|
@staticmethod
|
|
def center_window(toplevel: tk.Toplevel, parent: tk.Widget = None):
|
|
"""
|
|
Centers a Toplevel window on the screen or relative to a parent window.
|
|
|
|
If a parent is provided and visible, it attempts to center the toplevel
|
|
relative to the parent. Otherwise, it centers the toplevel on the screen.
|
|
|
|
Args:
|
|
toplevel (tk.Toplevel): The Toplevel window to center.
|
|
parent (tk.Widget, optional): The parent widget/window to center against.
|
|
Defaults to None (center on screen).
|
|
"""
|
|
toplevel.update_idletasks() # Ensure dimensions are calculated
|
|
|
|
# Get the requested width and height of the toplevel window
|
|
width = toplevel.winfo_reqwidth()
|
|
height = toplevel.winfo_reqheight()
|
|
|
|
# Fallback to screen centering if parent is not provided or not visible
|
|
center_x = toplevel.winfo_screenwidth() // 2
|
|
center_y = toplevel.winfo_screenheight() // 2
|
|
|
|
if parent and parent.winfo_viewable():
|
|
parent_x = parent.winfo_rootx()
|
|
parent_y = parent.winfo_rooty()
|
|
parent_width = parent.winfo_width()
|
|
parent_height = parent.winfo_height()
|
|
|
|
# Calculate center of the parent window
|
|
center_x = parent_x + (parent_width // 2)
|
|
center_y = parent_y + (parent_height // 2)
|
|
|
|
# Calculate position for top-left corner of toplevel
|
|
x = center_x - (width // 2)
|
|
y = center_y - (height // 2)
|
|
|
|
# Ensure the window is not placed off-screen (optional, but good practice)
|
|
screen_width = toplevel.winfo_screenwidth()
|
|
screen_height = toplevel.winfo_screenheight()
|
|
|
|
if x + width > screen_width:
|
|
x = screen_width - width
|
|
if y + height > screen_height:
|
|
y = screen_height - height
|
|
if x < 0:
|
|
x = 0
|
|
if y < 0:
|
|
y = 0
|
|
|
|
toplevel.geometry(f'{width}x{height}+{x}+{y}')
|
|
toplevel.transient(parent if parent else toplevel.master) # Make it a transient window if parent exists
|
|
try:
|
|
toplevel.grab_set() # Make the dialog modal
|
|
except tk.TclError:
|
|
# Can happen if the window is not yet mapped, but usually fine after update_idletasks
|
|
pass
|
|
toplevel.focus_set() # Set focus to the new window |