Handling widget resize with <Configure>

There might be occasions when you <indexentry content="window responsiveness:widget resize, handling with ">want to do some specific action when a user resizes a window or a widget. Tkinter provides an event named <Configure>, which can be bound to a callback to react to changes in widget size.

Here is a simple example (see handle_widget_resize.py):

from tkinter import Tk, Label, Pack

root= Tk()
label = Label(root, text = 'I am a Frame', bg='red')
label.pack(fill='both', expand=True)

def on_label_resized(event):
print('New Width', label.winfo_width())
print('New Height', label.winfo_height())

label.bind("<Configure>", on_label_resized)
root.mainloop()

The description of the code is as follows:

  • We have a Label widget in a root window. We set the pack options for the label to (fill='both', expand=True) as we want it to resize every time the root window resizes.
  • We attach a callback to the <Configure> event to listen for any changes in the size of the label widget. As soon as the label widget changes, it triggers a call to the method on_label_resized.

Now if you resize the window, the label resizes and that triggers on_label_resized, which prints the new height and width of the label widget to the console. This can be used for adjusting the placement of items on the screen.

That concludes our brief discussion on window responsiveness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.47.166