0

is there any method to count how many times a function is called in python? I'm using checkbutton in GUI. I have written a function for that checkbutton command, i need to perform some actions based on the checkbutton status, i mean based on whether it is ticked or not. My checkbutton and button syntax are like this

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

so i thougt of countin no. of times the command function is called, and based on its value i can decide whether it is ticked or not. please help

user19911303
  • 449
  • 2
  • 9
  • 34

2 Answers2

13

You can write decorator that will increment special variable after function call:

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)
Vladimir Lagunov
  • 1,895
  • 15
  • 15
  • 1
    Nice job there, this sure does work. However based on the OP's post; he's trying to see whether the checkbutton is ticked or not, and in that case this is not the best option. –  Nov 22 '12 at 12:23
2

If checking whether the checkbutton is ticked or not is the only thing you need, why not just do checkbutton.ticked = true?

One way to implement this is to create a sub class out of Checkbutton (or - if you can - edit the existing Checkbutton class) and just add self.ticked attribute to it.

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

And edit your function so that it changes your CheckbuttonPlus -object's ticked to not ticked.

I don't know how your classes are constructed, but you should find the method from Checkbutton class that activates the function, and then overwrite it in CheckbuttonPlus -class (incase you cannot edit the existing Checkbutton class, in which case, you don't even need CheckbuttonPlus class at all).

Edit: If you're using Tkinter Checkbutton (looks quite like it), you might wanna check this: Getting Tkinter Check Box State

Community
  • 1
  • 1
  • Thanks mahi. It sounds good, but i'm a beginner, and not knowing oops concepts. So can you please explain with a small example? – user19911303 Nov 22 '12 at 12:16
  • That would be pretty hard without seeing the code behind your Checkbutton class. If you could provide a small preview (method names fe.) about the Checkbutton class, and particularize what you're tying to achieve, I could help easier. –  Nov 22 '12 at 12:21