How do I bind to the Property type event in python?

Question:

I am trying to write a python tkinter program to investigate how I can make a responsive text. After reviewing certain tkinter articles. I decided that rowconfigure and columnconfigure is just not enough, since the font size of the text will also need to change. So I decided to bind to an event, such that whenever the windows size is changed, I can look at the windows size and decide the text font like is done in bootstrap js. My problem is that there is only one text I can find that explains how I can bind to a window resize event, but it is written for Tk/Tcl and I do not understand how that translates to python.

I can see from that file that I will need to do something like

root.bind("<Property>", on_resize_do_something_function)

but how do I specify the property name (size) which I want to watch for. Various hints are around the end of the page, but I do not understand how to translate them to python. Precisely, how I can bind to a property change event on a tk window in python? I posted a link to the page above in case it went unnoticed.

I will appreciate your help. Thanks in advance.

Asked By: Alphonsus

||

Answers:

If you’re trying to capture changes to the root window, such as the user resizing or moving the window, you can bind to the '<Configure>' event, e.g.:

def on_resize(e):
    global last_size  # allow this function to update the 'last_size' value
    # check if this event was generated by the root window
    # and if the size of the window has changed from the last event
    if str(e.widget) == '.' and (e.width, e.height) != last_size:
        ...  # do something!
        last_size = (e.width, e.height)  # update with the new root window size


root.bind('<Configure>', on_resize)
# get the initial size of the root window
last_size = (root.winfo_width, root.winfo_height)

Note that this event will fire immediately when the root window is created, but that’s not likely to cause issues in most cases

The Configure event object passed has the following properties:

  • event.x – the x position of the root window
  • event.y – the y position of the root window
  • event.width – the width of the root window
  • event.height – the height of the root window
Answered By: JRiggles
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.