[Python] Fixed aspect ratio for a window on Tkinter

Discussão em 'Python' iniciado por Stack, Maio 12, 2025.

  1. Stack

    Stack Membro Participativo

    I need to find out how to keep a constant aspect ratio for a window on Tkinter.

    I tried below code, but it only works when dragging bottom or top edges, but not for edges to the right or left. On all cases when dragging, the window is resized accordingly, but for non-ok cases when releasing, window's size returns to the size it had when I started dragging:

    import tkinter as tk

    class Window():
    _windowAspectRatio = None
    _resizing = False
    def __init__(self):
    self._root = tk.Tk()

    self._root.bind("<Configure>", self._on_resize)
    self._root.resizable(True,True)

    self._root.state("zoomed")

    self._root.update()#

    self._windowWidth = self._root.winfo_width()
    self._windowHeigth = self._root.winfo_height()
    self._windowAspectRatio = self._windowWidth/self._windowHeigth

    if 742/self._windowAspectRatio < 450:
    minHeight = 450
    minWidth = int(450 * self._windowAspectRatio)
    else:
    minHeight = int(742/self._windowAspectRatio)
    minWidth = 742

    self._root.minsize(minWidth,minHeight)

    def _on_resize(self,event):
    if event.widget == self._root:
    if not self._resizing:
    self._resizing = True
    widthToApply = self._root.winfo_width()
    heightToApply = self._root.winfo_height()
    if self._windowAspectRatio != None:
    desiredWidth = int(event.height * self._windowAspectRatio)
    desiredHeight = int(event.width / self._windowAspectRatio)
    if abs(event.width - self._windowWidth) > abs(event.height - self._windowHeigth):
    widthToApply = event.width
    heightToApply = desiredHeight
    else:
    widthToApply = desiredWidth
    heightToApply = event.height
    self._root.geometry(f"{widthToApply}x{heightToApply}")
    self._windowWidth = self._root.winfo_width()
    self._windowHeigth = self._root.winfo_height()
    self._root.update()
    self._resizing = False

    window = Window()

    def on_close():
    global running
    running = False

    window._root.protocol("WM_DELETE_WINDOW", on_close)

    running = True

    while running:
    window._root.update()

    Continue reading...

Compartilhe esta Página