2012-11-22 76 views
0

是否有任何方法來計算一個函數在Python中調用多少次? 我在GUI中使用checkbutton。我已經爲該checkbutton命令寫了一個函數,我需要根據checkbutton狀態執行一些操作,我的意思是根據是否打勾。我的checkbutton和按鈕的語法是這樣的要計數no。次函數被調用?

All = Checkbutton (text='All', command=Get_File_Name2,padx =48, justify = LEFT) 
submit = Button (text='submit', command=execute_File,padx =48, justify = LEFT) 

所以我thougt的計數沒有。命令函數被調用的次數,根據它的值我可以決定它是否被打勾。請幫助

+0

檢查按鈕沒有屬性或方法來提供它的當前狀態? –

+0

^你在用什麼框架,Tkinter? – 2012-11-22 12:27:29

+0

[在另一個方法中計數python方法調用]可能的重複(http://stackoverflow.com/questions/1301735/counting-python-method-calls-within-another-method) –

回答

2

如果檢查是否勾選了checkbutton是您唯一需要的,爲什麼不只是做​​?

實現此目的的一種方法是從Checkbutton創建一個子類(或者 - 如果可以的話 - 編輯現有的Checkbutton類)並將self.ticked屬性添加到它。

class CheckbuttonPlus(Checkbutton): 
    def __init__(self, text, command, padx, justify, ticked=False): 
     super().__init__(text, command, padx, justify) 
     self.ticked = ticked 

和編輯功能,使得它改變了你CheckbuttonPlus -object的勾選,藉此not ticked

我不知道你的類是如何構造的,但是你應該從Checkbutton類中找到激活該函數的方法,然後在CheckbuttonPlus -class中覆蓋它(因爲你不能編輯現有的Checkbutton類,在這種情況下,你甚至不需要CheckbuttonPlus類)。

編輯:如果你使用Tkinter的Checkbutton(看起來很喜歡它),你可能想要檢查: Getting Tkinter Check Box State

+0

感謝mahi。這聽起來不錯,但我是一個初學者,並不知道哎呀的概念。那麼你可以用一個小例子來解釋一下嗎? – user19911303

+0

如果沒有看到Checkbutton類背後的代碼,那將會非常困難。如果您可以提供有關Checkbutton類的小型預覽(方法名稱),並詳細說明您要實現的目標,我可以更輕鬆地幫助您。 – 2012-11-22 12:21:15

12

您可以編寫裝飾,將之後的函數調用增加特殊的變量:

from functools import wraps 

def counter(func): 
    @wraps(func) 
    def tmp(*args, **kwargs): 
     tmp.count += 1 
     return func(*args, **kwargs) 
    tmp.count = 0 
    return tmp 

@counter 
def foo(): 
    print 'foo' 

@counter 
def bar(): 
    print 'bar' 

print foo.count, bar.count # (0, 0) 
foo() 
print foo.count, bar.count # (1, 0) 
foo() 
bar() 
print foo.count, bar.count # (2, 1) 
+1

幹得不錯,這個確實有用。但是根據OP的帖子;他試圖查看是否勾選了checkbutton,在這種情況下,這不是最好的選擇。 – 2012-11-22 12:23:55