对于上下文,我有一个用于生成按钮的函数。当按下按钮时,函数的最后两个参数用于使另一个函数变得有趣。
当按下按钮时我试图调用函数(和参数)createWorksheet(sheetTitle,sheetDate,sheetFilename)时,我遇到了这样的按钮问题。
我的目标是使用此代码:
button("Create Sheet",200,500,200,50,GREEN,BRIGHTGREEN,createWorksheet,sheetTitle,sheetDate,sheetFilename)
但这会产生错误
button() takes from 7 to 9 positional arguments but 11 were given
相反,我尝试使用元组中的参数(如下所示)
button("Create Sheet",200,500,200,50,GREEN,BRIGHTGREEN,createWorksheet,(sheetTitle,sheetDate,sheetFilename))
但这会引发错误:
createWorksheet() missing 2 required positional arguments: 'date' and 'filename'
有什么想法吗?
这是生成函数的按钮代码
def button(text, posX, posY, width, height, inactiveColor, activeColor,action=None,actionArgs=None):
global buttonDown
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if posX + width > mouse[0] > posX and posY + height > mouse[1] > posY:
pygame.draw.rect(displays, activeColor, (posX,posY, width, height))
if click[0] == 1 and not buttonDown and action!= None:
if actionArgs is not None:
action(actionArgs)
else:
action()
buttonDown = True
elif click[0] == 0:
buttonDown = False
else:
pygame.draw.rect(displays,inactiveColor,(posX,posY,width,height))
textSurf, textRect = text_objects(text, smallfont)
textRect.center = ( (posX + (width/2)), (posY+(height/2)) )
displays.blit(textSurf, textRect)
答案 0 :(得分:0)
我认为第二次调用,即使用args的元组,是正确的。但是,您需要将参数作为位置参数传递给action
函数,而不是作为元组。
您没有显示createWorksheet()
的定义,但假设它从您的示例中获取了3个参数,您可以这样称呼它:
if actionArgs is not None:
action(*actionArgs)
else:
action()
这个将元组解包成单独的值,并将它们传递给函数。区别在于:
args = (sheetTitle, sheetDate, sheetFilename)
action(args) # passes a single argument of type tuple
VS
action(*args) # passes each element of the tuple as a positional argument.
第二种情况与:
相同action(sheetTitle, sheetDate, sheetFilename)
如果只有一个参数要传递,你仍然需要将它作为一个元素元组传递给button()
,如下所示:
button("Create Sheet",200,500,200,50,GREEN,BRIGHTGREEN,createWorksheet,(sheetTitle,))