[Tutor] Getting name of Widget for event.widget?
Peter Otten
__peter__ at web.de
Wed Jul 25 18:27:06 CEST 2012
Leam Hall wrote:
> Note that this is for an on-line class so I'd appreciate pointers to
> what I need to read or think about more than the answer out right.
>
> Using Python 3 on Linux, is there a way to get the name of a widget
> instead of numeric representations in event.widget?
>
> What I tried were a few variations of:
>
> def small_frame_handler1(self, event):
> print(event.widget, " clicked at ", event.x, event.y)
>
> and got:
>
> .140937484.144713004 clicked at 350 39
The above is actually a name in Tcl, automatically generated by tkinter.
> Called by:
>
> frame1 = Frame(self, bg="blue")
> frame1.grid(row=0, column=0, rowspan=1, columnspan=2, sticky=ALL)
> frame1.bind("<Button-1>", self.small_frame_handler1)
>
> I tried to send parameters in the "bind" but kept getting argument
> mis-matches. There are two frames and I'd like to be able to put the
> name of the frame in the print without having to have a separate method
> for each one. This is inside a class, if that makes a difference.
You can either provide a custom name (tkinter will still add a leading dot)
import tkinter as tk
root = tk.Tk()
def frame_handler(event):
print(event.widget)
for row, color in enumerate(["red", "blue"]):
frame = tk.Frame(root, bg=color, name=color + "_frame")
frame.grid(row=row, column=0, sticky="nsew")
frame.bind("<Button-1>", frame_handler)
root.rowconfigure(row, weight=1)
root.columnconfigure(0, weight=1)
root.geometry("200x200+100+200")
root.mainloop()
set a custom attribute
...
def frame_handler(event):
print(event.widget.my_name)
for row, color in enumerate(["red", "blue"]):
frame = tk.Frame(root, bg=color)
frame.my_name = color + "_frame"
frame.grid(row=row, column=0, sticky="nsew")
frame.bind("<Button-1>", frame_handler)
root.rowconfigure(row, weight=1)
...
or use a more general mechanism with functools.partial:
import tkinter as tk
from functools import partial
root = tk.Tk()
def frame_handler(event, widget_name):
print(widget_name)
for row, color in enumerate(["red", "blue"]):
frame = tk.Frame(root, bg=color)
frame.grid(row=row, column=0, sticky="nsew")
frame.bind("<Button-1>", partial(frame_handler, widget_name=color +
"_frame"))
...
More information about the Tutor
mailing list