Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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], ...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading