user3292534
user3292534

Reputation:

tkinter - pass event to a function

When I do

def popup(event):
    menu.post(event.x_root, event.y_root)

'event' get highlighted by PyCharm and processed ok by python. When I do

something.bind("<SomeKey>", foo(event,bar,INSERT))

'event' is not highlighted, and I get exception:

NameError: name 'event' is not defined

How are these two different? If python found event implicitly in first case, why it cannot do the same again?

Upvotes: 2

Views: 2002

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385810

When you call bind, you must give it a reference to something that can be called at a later time. You are not doing that -- you are calling foo at the time you are calling bind. Because you are calling the function, at that time the variable event doesn't exist, so you get the error.

The best thing to do is to define foo such that you don't need to pass it arguments. It's not best in a general sense per se, just best for when you are first learning Tkinter. Since tkinter automatically passes an event object, you need for it to accept that argument, but you don't need to pass that argument explicitly.

For example:

def foo(event):
    global bar
    <do something with event, bar and INSERT>

something.bind("<SomeKey>", foo)

Notice that there are no extra parenthesis in the bind statement. The foo function is passed to the bind command, and tkinter will automatically include an event object when it calls foo.

Upvotes: 1

Related Questions