Home > Mobile >  Passing functions as input to another function in another script (Python)
Passing functions as input to another function in another script (Python)

Time:03-12

to avoid writing many times similar GUIs for my very basic python programs, I've written a GUI generator function in a standalone script like this:

def GUI_builder_function(entry_list, entry_default_list, button_list, function_list, panel_title, background_colour):
    #Entries Generation

    ....

    #Buttons Generation
    for i in range(0, N_buttons,1):
        button = tk.Button(text = button_list[i], command= (lambda i=i: eval(function_list[i].__name__  "()")), bg = 'firebrick', fg = 'white', font = ('helvetica', 9, 'bold'))
        input_data_panel.create_window(0.5*pos_width 300, 0.35*pos_height*(2*i 1)   20, window = button)
        buttons.append(button)
...

It's a very simple GUIgenerator which creates some entries and buttons corresponding to the input entry list and button list, and space them in a decent way.

Now, my problem is that: when the user clicks the generic i-th button, it must execute the function function_list[i] that the caller function has sent to the gui builder function.

However, despite the gui builder function has received function_list[i] as an input, it cannot execute it when the button is pressed. The python engine says:

"Name 'function name' is not defined".

Of course it is defined in the caller function. But it will be dirty to import each caller function of each program inside the common gui builder function. What I'm looking for is how to send to gui builder the function definition as an input to the gui builder function, which is in a standalone script as it must be utilized by different programs.

CodePudding user response:

You just reference the function directly, if I understand the problem correctly, and assuming function_list is actually a list of functions rather than a list of strings representing function names.

def foo():
    pass
def bar():
    pass

function_list = [foo, bar]
...
button = tk.Button(..., command= function_list[i], ...)
  • Related