Overwriting default events

What happens if we bind a key which already has default behavior on the target widget? Let's take a look at one example. You should remember from our text editor example that the combination of Ctrl + O inserted blank lines. We should overwrite that:

import tkinter as tk

win = tk.Tk()

text = tk.Text(win, fg="black", bg="white")

text.bind('<Control-o>', lambda e, t=text: t.insert(1.0, 'aaa'))

text.pack()
win.mainloop()

Run this example, type three lines of dummy text, then place your cursor in the middle somewhere. When you press Ctrl + O, you would expect the letters aaa to be inserted at the beginning of the editor. Well, they are, but the default behavior of adding blank lines also happens. If we are going to bind this shortcut to open a file, we don't want blank lines being added into the current file first!

When an event occurs in Tkinter, it will propagate from the instance level down to the class level. This means that any bindings which occur on the Text widget class itself, not specifically our instance, will also happen. This is why we get the additional blank lineā€”the behavior has been bound to the Text widget at a class level.

To prevent this propagation, we need to return the string break during the instance level bindings.

Update the previous code snippet to do this:

def on_control_o(event=None):
t.insert(1.0, 'aaa')

return "break"

t.bind('<Control-o>', on_control_o)

When running this version of the code, pressing Ctrl + o will only add the aaa characters and no longer create the blank lines. This is because returning the special break string has prevented Tkinter from passing the keyboard event down to the class level.

With that cleared up, the last thing to look at regarding events is generating them.

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

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