0

When the window is resized, I want the height to be set equal to the width so the windows always is a square. In the code below print(event.width) does print the new window width, but canvas.configure(height=event.width) doesn't change the canvas height. What am I doing wrong?

EDIT: I want the whole window to stay squared.

import tkinter as tk
from timeit import default_timer as timer

start_timer = timer()

height = 600
width = 600

red = ("#ff7663")

root = tk.Tk()

canvas = tk.Canvas(root, height=height, width=width, background=red)
canvas.pack(expand=True,fill="both")

def resize(event):
    end_timer = timer()
    if end_timer - start_timer > 0.5:
        print(event.width)
        canvas.configure(height=event.width)

canvas.bind("<Configure>", resize)

root.mainloop()```

4
  • I think the binding needs to be on the root window: root.bind("<Configure>", resize). But to be honest I'm not sure I understand what issue you're having. When I canvas.pack(expand=True,fill="both"), the canvas automatically takes up the whole root window regardless of its initial width or height, and fills the window on resize. Do you want the canvas to be square even when the root window isn't? Commented Nov 28, 2022 at 21:13
  • 1
    Are you wanting the whole window to stay square, or only the canvas? Commented Nov 28, 2022 at 21:25
  • My bad, I want the whole window to stay squared. Commented Nov 28, 2022 at 21:34
  • I've been looking into root.wm_aspect (i.e., tk.aspect), but apparently it doesn't work...I'm at a loss, I'm afraid. Commented Nov 29, 2022 at 13:40

2 Answers 2

1

Changing the size of the canvas won't override the size created by the user. If you're wanting the whole window to remain square you must explicitly set the size of the window.

For example:

def resize(event):
    width = root.winfo_width()
    root.wm_geometry(f"{width}x{width}")
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure if this is what you're after, but this example maintains a square canvas regardless of window size*:

import tkinter as tk

root = tk.Tk
root.geometry('600x600')
canvas = tk.Canvas(root, background=red)
canvas.pack()


def on_resize(event):
    w, h = event.width, event.height
    if w <= h:
        canvas.configure(width=w, height=w)


if __name__ == '__main__':
    root.bind('<Configure>', on_resize)
    root.mainloop()

*Unless the window is resized to be narrower/shorter than the initial geometry given

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.