我正在使用PyQt並希望基於字符串列表創建菜單。Python動態函數生成
問題是,當我想調用'addAction'時,它需要一個不帶任何參數的回調函數(對於每個字符串)。
對於簡單的菜單,這樣可以:
menu.addAction("Open", self.open)
menu.addAction("Exit", self.quit)
但是,我想只使用一個函數,並將'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
這裏是我的代碼片段:
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)
任何建議,不勝感激
「使用閉包」。閉包只是一個關閉封閉範圍內的自由變量的函數。 – 2011-07-13 17:03:18
@pst:不,那是因爲'functools.partial'的存在而重新發明輪子。加上「封閉」是一個更廣泛的概念;) – delnan
@delan :)你是什麼意思,封閉是一個更廣泛的概念? – 2011-07-13 19:07:25