event handling in classes?

Nick Belshaw nickb at earth.ox.ac.uk
Mon Jun 7 13:57:31 CEST 1999


bgue at my-deja.com wrote:

> Hi, I'm stumped on how to accomplish event handling with a Tkinter app
> that's a class. I didn't find anything on a Dejanews search either...can
> anybody tell me what the following example is doing wrong?
>
> from Tkinter import *
>
> class gui(Frame):
>   def __init__(self, parent=None):
>     Frame.__init__(self, parent)
>     self.grid()
>     self.bind("<Key>", self.callback)
>     self.str = ""
>     self.mainloop()
>
>   def callback(self, event):
>     print event.char
>     self.str = self.str + event.char
>
> g = gui()
>
> -----

I don't see any replies so I'll try a little clumsy help.

Your code seems a bit confused so if I modify it slightly....
#---------------------------------------
from Tkinter import *

class gui(Frame):
  def __init__(self, parent=None):
    self.test_widget1 = Canvas(parent,width=50,height=50)
    self.test_widget1.pack()
    self.test_widget1.bind('<1>', self.callback)

    self.test_widget2 = Text(parent,width=10,height=10)
    self.test_widget2.pack()
    self.test_widget2.bind('<Key>', self.callback)

  def callback(self, event):
    print event

Main = Tk()
g = gui(Main)
Main.mainloop()
#----------------------------------------
Same class approach but I have initialised a master-window with Tk() and
passed
it to the instance on creation and finally started the Tk.event-loop
outside the instance with Main.mainloop()

Your main problem is with the widget bindings. You can only bind things to
a widget that the widget can recognise.

So the Canvas will recognise the mouse '<1>' press but if you bind a
<KeyPress> it will not see it.
A Text widget will then see the <Key> event ok of course.

You had a Frame which might take entry and motion bindings (not sure -
maybe none) but a Frame is a holder for other widgets.

Anyway - hope that sets you on the right track.

For more info try

http://www.pythonware.com/library.htm

cheers
Nick/Oxford






More information about the Python-list mailing list