简体   繁体   中英

Tkinter Event/Geometry Propagation

I am currently building my own text editor in Tkinter, and I am struggling to understand what event and geometry propagation is and how it works. I have dug all over the internet to find a definite answer, but I have yet to find one.

With that said, can someone please give me the rundown of what propagation is for events and the geometry manager? I feel like having a post focused on propagation will be beneficial to me and many other Tk/Tkinter users.

Here are some specific examples of what confuses me:

This method autocompletes curly braces, but why must I return "break" to have this work properly? Some other StackOverflow post (can't find it anymore) said that it stops the event from further propagating, but I do not know what this means.

def _curly_pressed(self, event):
    self.text_field.insert(INSERT, "{}")
    self.text_field.mark_set(INSERT, f"{self.text_field.index(INSERT).split('.')[0]}.{int(self.text_field.index(INSERT).split('.')[1]) - 1}")
    return "break"

Furthermore, I wanted to keep the window from resizing when the Text widget fills with text. To do this, I had to use the grid_propogate method on the Frame containing the Text widget. I do not understand this, though.

self.grid_propagate(False)

An event can be bound to a widget, such as an instance of Text, to a widget class, such as Text, or all widgets. For the first, this reference says

w.bind(sequence=None, func=None, add=None)

This method is used to attach an event binding to a widget. See Section 54, “Events” for the overview of event bindings.

The sequence argument describes what event we expect, and the func argument is a function to be called when that event happens to the widget. If there was already a binding for that event for this widget, normally the old callback is replaced with func, but you can preserve both callbacks by passing add='+'.

If you bound two events to a widget, the first event handler could specify whether it handled the event or not by returning 'break' or None.

Binding an event to a widget does not replace class and all bindings. The Text class has an event handler for all visible key events, which inserts the character into the Text instance. You did not say what did not work properly, but I presume that without 'break', the Text key event handler inserted another '{' character. Since your handler already does that, you want to prevent the second insertion with 'break'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM