简体   繁体   English

将函数作为输入传递给另一个脚本中的另一个 function (Python)

[英]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:为了避免为我非常基本的 python 程序编写多次类似的 GUI,我在独立脚本中编写了一个 GUI 生成器 function ,如下所示:

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.这是一个非常简单的 GUIgenerator,它创建一些对应于输入条目列表和按钮列表的条目和按钮,并以适当的方式将它们隔开。

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 .现在,我的问题是:当用户单击第 i 个通用按钮时,它必须执行调用者 function 已发送给 gui 生成器 function 的 function function_list[i]

However, despite the gui builder function has received function_list[i] as an input, it cannot execute it when the button is pressed.然而,尽管 gui 构建器 function 已接收到 function_list[i] 作为输入,但在按下按钮时它无法执行它。 The python engine says: python 引擎说:

"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 .当然它是在调用者 function 中定义的。但是将每个程序的每个调用者 function 导入公共 gui 构建器 function 中是很脏的。我正在寻找的是如何将 function 定义作为输入发送到 gui 构建器gui builder function,它是一个独立的脚本,因为它必须被不同的程序使用

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.您只需直接引用 function,如果我理解正确,并假设function_list实际上是函数列表而不是表示 function 名称的字符串列表。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM