我正在使用PyQt,并希望基于字符串列表创建菜单.
问题是,当我想调用'addAction'时,它需要一个不带任何参数的回调函数(对于每个字符串).
对于简单的菜单,这很好:例如
menu.addAction("Open", self.open)
menu.addAction("Exit", self.quit)
Run Code Online (Sandbox Code Playgroud)
但是,我想只使用一个函数并将'action string'作为参数传入.
我想知道python是否可以做这样的事情:
def f(x, y):
print x + 2*y
# These 2 variables are of type: <type 'function'>
callback1 = f
callback2 = f(x=7, *)
# NB: the line above is not valid python code.
# I'm just illustrating my desired functionality
print callback1(2,5) # prints 12
print callback2(5) # prints 17
Run Code Online (Sandbox Code Playgroud)
这是我的代码片段:
def printParam(parameter):
print "You selected %s" % parameter
# parameters = list of strings
menu_bar = QMenuBar()
menu = menu_bar.addMenu('Select Parameter')
for parameter in parameters:
# This line will not work because the action does not pass in
# any arguments to the function
menu.addAction(parameter, printParam)
Run Code Online (Sandbox Code Playgroud)
任何建议都非常感谢
functools.partial()允许您提前提供一些参数.它允许您根据需要进行自定义回调.
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18
Run Code Online (Sandbox Code Playgroud)