【问题标题】:How to resize root window size with aspect ratio in tkinter?如何在 tkinter 中使用纵横比调整根窗口大小?
【发布时间】:2021-08-01 16:04:21
【问题描述】:

我该怎么做(如果任何用户尝试调整窗口宽度大小也会自动调整窗口高度的纵横比。这意味着用户不能只调整一个大小。改变一侧的大小也会改变另一侧。 )?

【问题讨论】:

  • 能否详细说明一下
  • @Sujay 好的,我想制作一个 2:3 大小的窗口。如果 root.resizable(width=True, height=True) 则用户只能更改宽度或仅更改高度或同时更改两者。但是仅更改高度或仅更改宽度会破坏窗口纵横比(2:3)。有没有什么办法可以让只拖动窗口 x 边来增加宽度,那么程序会自动增加高度以保持窗口纵横比不变。
  • @ArmenGhazaryan 我不想调整框架大小。我想调整窗口大小。

标签: python tkinter


【解决方案1】:

(在仔细阅读了您在描述您希望它如何工作的问题下发表的评论后,我再次修改了代码以使其如此。)

您可以通过在绑定到根窗口的事件处理程序中处理'<Configure>' 事件来实现。这很棘手,因为当您将绑定添加到根窗口时,它也会添加到它包含的 每个 小部件中——因此需要能够在事件处理程序中区分它们和根窗口.在下面的代码中,这是通过检查event.widget.master 属性是否为None 来完成的,这表明正在配置的小部件是根窗口,它没有。

代码创建根窗口并将根窗口大小调整事件绑定到将保持所需纵横比的事件处理函数。当检测到根窗口的调整大小事件时,该函数会检查新大小的纵横比以查看它是否具有正确的比例,如果不是,它会阻止事件的进一步处理,并手动设置窗口的大小到一个宽度和高度。

import tkinter as tk
WIDTH, HEIGHT = 400, 300  # Defines aspect ratio of window.

def maintain_aspect_ratio(event, aspect_ratio):
    """ Event handler to override root window resize events to maintain the
        specified width to height aspect ratio.
    """
    if event.widget.master:  # Not root window?
        return  # Ignore.

    # <Configure> events contain the widget's new width and height in pixels.
    new_aspect_ratio = event.width / event.height

    # Decide which dimension controls.
    if new_aspect_ratio > aspect_ratio:
        # Use width as the controlling dimension.
        desired_width = event.width
        desired_height = int(event.width / aspect_ratio)
    else:
        # Use height as the controlling dimension.
        desired_height = event.height
        desired_width = int(event.height * aspect_ratio)

    # Override if necessary.
    if event.width != desired_width or event.height != desired_height:
        # Manually give it the proper dimensions.
        event.widget.geometry(f'{desired_width}x{desired_height}')
        return "break"  # Block further processing of this event.

root = tk.Tk()
root.geometry(f'{WIDTH}x{HEIGHT}')
root.bind('<Configure>', lambda event: maintain_aspect_ratio(event, WIDTH/HEIGHT))
root.mainloop()

【讨论】:

    猜你喜欢
    • 2018-06-11
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多