将函数作为输入传递给另一个脚本中的另一个函数 (Python)
为了避免为我的非常基本的Python程序编写多次类似的GUI,我在一个独立的脚本中编写了一个GUI生成器函数,如下所示:
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)
...
这是一个非常简单的GUI生成器,它创建了一些与输入条目列表和按钮列表,并以适当的方式间隔它们。
现在,我的问题是:当用户单击通用第 i 个按钮时,它必须执行调用者函数已发送到 gui 构建器函数的函数 function_list[i]。
然而,尽管 gui 构建器函数已收到 function_list[i] 作为输入,但按下按钮时它无法执行它。 python引擎说:
“名称'函数名称'未定义”。
当然它是在调用函数中定义的。但是将每个程序的每个调用者函数导入公共 gui 构建器函数中会很脏。 我正在寻找的是如何将函数定义发送到 gui 构建器作为 gui 构建器函数的输入,该函数位于独立脚本中,因为它必须由不同的程序使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解问题,并且假设 function_list 实际上是函数列表而不是表示函数名称的字符串列表,那么您只需直接引用该函数即可。
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.