Passing Variables to Button Functions[SOLVED]

I’ve found that if I define a buttons command in the following manner it does not appear to call the function.

 button["command"] = function()

but if I remove the parenthesis after the function, it works just fine. Like this:

button["command"] = function

This makes me wonder, how would I pass variables into a function that is called by a button?

When you say:

 button["command"] = function()

you are calling function() on the spot, and assigning the return value of that call, whatever it is, as the button command. Since the return value is likely None, then you are really assigning None to the button command, which means to do nothing when the button is clicked.

When you say:

 button["command"] = function

you are assigning the function itself to the button command.

The DirectButton class has a special interface for passing additional arguments to whatever function you give it:

 button["command"] = function
 button["extraArgs"] = [arg1, arg2, arg3]

This means it will call function(arg1, arg2, arg3) when you click the button.

But you don’t actually need to use this special syntax. Any time you want to pass a function pointer with its bound arguments, you can just create a functor, which is exactly that: a function pointer with bound arguments. A functor is really just a function that takes no arguments that was created on-the-fly, and when this function is called, it turns around and calls whatever function you specified, with the arguments you specified. One easy way to create a functor is in PythonUtil:

from direct.showbase.PythonUtil import Functor
button["command"] = Functor(function, arg1, arg2, arg3)

David

1 Like

Thanks again David. I really should have realized that one. You’ve got the patience of a saint.