2017-02-13 82 views
-1

對於上下文,我有一個用於生成按鈕的函數。當按鈕被按下時,函數的最後兩個參數用於調用另一個函數。函數中的Python參數

當按鈕被按下時,Im試圖調用函數(和參數)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

你期待什麼發生?我想你想要的是一個''lambda''或'functools.partial'封裝'createWorksheet'幷包含這些附加參數,但不清楚爲什麼你認爲你可以像這樣通過它們;這個不成立。 – jonrsharpe

+1

'action(actionArgs)'將元組作爲單個參數傳遞,而不是將其解包。 – user2357112

+0

@ user2357112我將如何解開它? – benjo456

回答

0

我認爲第二次調用,即,使用一個元組的指定參數時,是正確的。但是,您需要將參數作爲位置參數傳遞給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 

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,)) 
+0

謝謝。問題現在已修復。對此,我真的非常感激 – benjo456