0

有什么方法可以计算一个函数在python中被调用多少次?我在 GUI 中使用复选按钮。我已经为该 checkbutton 命令编写了一个函数,我需要根据 checkbutton 状态执行一些操作,我的意思是基于它是否被勾选。我的检查按钮和按钮语法是这样的

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

所以我认为没有。调用命令函数的次数,根据它的值我可以决定它是否被勾选。请帮忙

4

2 回答 2

13

您可以编写装饰器,在函数调用后增加特殊变量:

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)
于 2012-11-22T12:09:46.310 回答
2

如果检查检查按钮是否被勾选是您唯一需要做的事情,为什么不直接做checkbutton.ticked = true呢?

实现这一点的一种方法是从 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

于 2012-11-22T12:07:04.110 回答