Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Global Binding

Is it possible to bind all widgets to one command, with a single line? It would be nice if I could type in one line as opposed to doing each widget individually.

like image 852
rectangletangle Avatar asked Apr 03 '26 03:04

rectangletangle


1 Answers

You would use the bind_all method on the root window. This will then apply to all widgets (unless you remove the bindtag "all" from some widgets). Note that these bindings fire last, so you can still override the application-wide binding on specific widgets if you wish.

Here's a contrived example:

import Tkinter as tk

class App:
    def __init__(self):
        root = tk.Tk()
        root.bind_all("<1>", self.woot)
        label1 = tk.Label(text="Label 1", name="label1")
        label2 = tk.Label(text="Label 2", name="label2")
        entry1 = tk.Entry(name="entry1")
        entry2 = tk.Entry(name="entry2")
        label1.pack()
        label2.pack()
        entry1.pack()
        entry2.pack()
        root.mainloop()

    def woot(self, event):
        print "woot!", event.widget

app=App()

You might also be interested in my answer to the question How to bind self events in Tkinter Text widget after it will binded by Text widget? where I talk a little more about bindtags.

like image 132
Bryan Oakley Avatar answered Apr 08 '26 19:04

Bryan Oakley