I the following code I want to bind all frame1 items to <'Enter'> Event, but it does not work. I mean canvas.focus_set() does not take effect. How can I solve my problem?
for w in frame1.winfo_children():w.bind('<Enter>',canvas1.focus_set())
I the following code I want to bind all frame1 items to <'Enter'> Event, but it does not work. I mean canvas.focus_set() does not take effect. How can I solve my problem?
for w in frame1.winfo_children():w.bind('<Enter>',canvas1.focus_set())
The comment made by Lafexlos actually sends you in the right direction. When you do
w.bind('<Enter>', canvas1.focus_set())
you call canvas1.focus_set()
and use the return value of this function call (which is None
) to bind to the event. This isn't what you want, because now every time the event is triggered, None
is executed instead of canvas1.focus_set()
.
What you should do is pass a function reference to the bind
function. The reference for calling canvas1.focus_set()
is canvas1.focus_set
. However, using
w.bind('<Enter>', canvas1.focus_set)
still doesn't work.
This is because the bind
function passes an event object to the function it has been given, so it will call canvas1.focus_set(event)
instead of canvas1.focus_set()
. Because focus_set
does not accept any arguments, this fails.
You can fix this in two ways. You could make an extra function, which does accept an event object and then calls canvas1.focus_set()
without arguments, and then bind the event to this new function. The other option is to use an anonymous "lambda" function to basically do the same like
w.bind('<Enter>', lambda e: canvas1.focus_set())
This way the lambda function accepts the event object as e
, but doesn't pass it to focus_set
.
P.S. The <Enter>
event is not the event that is triggered when you press the Enter button on your keyboard (that is <Return>
). The <Enter>
event is triggered whenever you move the mouse onto a widget and is accompanied by the <Leave>
event for when you leave the widget with your mouse. This might be what you want, but it often leads to confusion.