Home > database >  Python Canvas bind and resize
Python Canvas bind and resize

Time:11-29

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?

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()```

CodePudding user response:

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}")

CodePudding user response:

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

  • Related