Search code examples
pythonpysimplegui

I want to fix the aspect ratio of a window in PySimpleGUI


I want to fix the aspect ratio of a window in PySimpleGUI.

I would like to automatically update the height to match the entered aspect ratio based on the width of the resizable window. I've been searching but haven't found any relevant information.

I tried to adjust the Windows size using Win32Gui.movewindow, but it doesn't work properly.

python win32com.client resize window

def keep_aspect_ratio(target_width, target_height, window_name):

if not((target_width == 0) or (target_height == 0)):
    try:
        hwnd = win32gui.FindWindow(None, window_name)
        
        bar_thickness = get_title_bar_thickness(hwnd)
        
        add_w = target_width + 22
        
        add_h = target_height + bar_thickness
        
        if hwnd:
            x0, y0, x1, y1 = win32gui.GetWindowRect(hwnd)
            
            w = x1 - x0 
            h = y1 - y0
            target_ratio = add_w/add_h
            current_ratio = w/h
            
            print(w, h, bar_thickness, add_w, add_h, target_ratio, current_ratio)
            
            new_h = int(w/target_ratio)
            
            if not new_h == h:
                win32gui.MoveWindow(hwnd, x0, y0, w, new_h, True)
    except:
        pass

Solution

  • import PySimpleGUI as sg
    
    def keep_aspect_ratio(window, target_ratio):
        width, height = window.Size
        current_ratio = width / height
    
    if current_ratio != target_ratio:
            new_width = int(height * target_ratio)
            window.Size = (new_width, height)
    
    layout = [
        [sg.Text("Enter aspect ratio:")],
        [sg.Input(key="aspect_ratio")],
        [sg.Button("Update Aspect Ratio")],
        [sg.Text("Resize the window to see the aspect ratio in action")],
    ]
    
    window = sg.Window("Aspect Ratio Example", layout, resizable=True)
    
    while True:
        event, values = window.read()
    
    if event == sg.WINDOW_CLOSED:
            break
    elif event == "Update Aspect Ratio":
            try:
                target_ratio = float(values["aspect_ratio"])
                keep_aspect_ratio(window, target_ratio)
            except ValueError:
                sg.popup_error("Please enter a valid aspect ratio")
    
    window.close()