Decorator Recipe: Event Binding in Tkinter

Step 1

Subclass Tkinter's Button class and give it a decorator method.

from Tkinter import *

class MyButton(Button):
    """Add a method to this class"""

if __name__ == '__main__':
    frame = Frame()
    frame.master.title("Event binding with decorators")
    frame.pack()

    btn1 = MyButton(frame, text="One")
    btn1.pack()

    btn2 = MyButton(frame, text="Two")
    btn2.pack()

    @btn1.command
    @btn2.command
    def onclick():
        print 'You clicked on a button'

    frame.mainloop()

Expected output:

tkinter-screenshot.png

Hints:

  1. Show hint
  2. Show hint
  3. Show hint
  4. Show hint

Solution: tkinter1.py

Go to next step