Home > Net >  Can I combine two bindings?
Can I combine two bindings?

Time:12-17

I want to update a widgets on a canvas widget when the window is resized. You can bind a function call on window resize via the <Configure> flag:

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

However, this calls resize continuously while the window is being updated, many times per second. What would be better is if I could call resize after the window has been resized. So I imagine, once MB1 has been released.

So can I combine bindings? I need to combine both <Configure> and <ButtonRelease-1>

I was thinking of creating a global variable that contains the state of MB1, and updating this state via <ButtonRelease-1> and <ButtonPress-1> but I'm wondering if there's a lass hacky method.

CodePudding user response:

A simple solution is to not do the work immediately, but instead schedule it for some time in the future. Each time the <Configure> event is handled you can cancel any previously scheduled work before scheduling the work again.

The following example shows how to update a label in the middle of a frame on <Configure>, but only after the window size hasn't changed for 200ms.

import tkinter as tk

def handle_configure(event):
    global after_id
    if after_id:
        event.widget.after_cancel(after_id)
    after_id = event.widget.after(200, update_label)

def update_label():
    width = root.winfo_width()
    height = root.winfo_height()
    text = f"Size: {width}x{height}"
    label.configure(text=text)

root = tk.Tk()
frame = tk.Frame(root, width=400, height=400)
frame.pack(fill="both", expand=True)

label = tk.Label(frame, text="")
label.place(relx=.5, rely=.5, anchor="c")

after_id = None
frame.bind("<Configure>", handle_configure)

root.mainloop()
  • Related