Tkinter.event.widget: handler gets name instead of widget.

Terry Reedy tjreedy at udel.edu
Mon Jul 9 15:45:38 EDT 2012


On 7/9/2012 1:49 PM, Rick Johnson wrote:
> On Jul 9, 12:58 am, Terry Reedy <tjre... at udel.edu> wrote:
>> When posting problem code, you should post a minimal, self-contained
>> example that people can try on other systems and versions. Can you
>> create the problem with one record, which you could give, and one
>> binding? Do you need 4 fields, or would 1 'work'?
>
> I'll firmly back that sentiment. Fredric, if you cannot get the
> following simple code events to work properly, then how do you think
> you can get events working properly on something more complex?
>
> ## START CODE ARTISTRY ##
> import Tkinter as tk
> from Tkconstants import *
>
> class MyFrame(tk.Frame):
>      def __init__(self, master, **kw):
>          tk.Frame.__init__(self, master, **kw)
>          self.bind('<Enter>', self.evtMouseEnter)
>          self.bind('<Leave>', self.evtMouseLeave)
>          self.bind('<Button-1>', self.evtButtonOneClick)
>
>      def evtMouseEnter(self, event):
>          event.widget.config(bg='magenta')
>
>      def evtMouseLeave(self, event):
>          event.widget.config(bg='SystemButtonFace')
>
>      def evtButtonOneClick(self, event):
>          event.widget.config(bg='green')
>
> if __name__ == '__main__':
>      root = tk.Tk()
>      for x in range(10):
>          f = MyFrame(root, height=20, bd=1, relief=SOLID)
>          f.pack(fill=X, expand=YES, padx=5, pady=5)
>      root.mainloop()
> ## END CODE ARTISTRY ##

I copied and pasted this self-contained code into a 3.3 Idle edit window 
and lightly edited for 3.x. Change 'Tkinter' to 'tkinter', remove 
tkconstants import and prefix constants with 'tk.'. (The alternative: 
change 'tkconstants' to 'tkinter.constants', but I prefer prefixes). It 
runs as expected.

import tkinter as tk

class MyFrame(tk.Frame):
     def __init__(self, master, **kw):
         tk.Frame.__init__(self, master, **kw)
         self.bind('<Enter>', self.evtMouseEnter)
         self.bind('<Leave>', self.evtMouseLeave)
         self.bind('<Button-1>', self.evtButtonOneClick)

     def evtMouseEnter(self, event):
         event.widget.config(bg='magenta')

     def evtMouseLeave(self, event):
         event.widget.config(bg='SystemButtonFace')

     def evtButtonOneClick(self, event):
         event.widget.config(bg='green')

if __name__ == '__main__':
     root = tk.Tk()
     for x in range(10):
         f = MyFrame(root, height=20, bd=1, relief=tk.SOLID)
         f.pack(fill=tk.X, expand=tk.YES, padx=5, pady=5)
     root.mainloop()

Add details and data (maybe less than 10 records) until you get what you 
want or recreate problem.

-- 
Terry Jan Reedy






More information about the Python-list mailing list