0

I'm trying to create a simple Gui with tkinter using classes. But I don't really understand how to make the for-loop work inside the count method, could anyone tell me where should I add the missing argument?

from tkinter import *
import time


class App:

    def __init__(self, master):
        self.container1 = Frame(master)
        self.container1.pack()
        self.button1 = Button(self.container1, text="count")
        self.button1.bind("<Button-1>", self.count)
        self.button1.pack()

    def count(self):
        for i in range(100):
            self.button1["text"] = str(i)
            time.sleep(1)


root = Tk()
Myapp = App(root)
root.mainloop()

The error is:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
TypeError: count() takes 1 positional argument but 2 were given

1 Answer 1

2

When you bind an event, a positional argument event is provided to the callback function.

Change your count method to this:

def count(self, event):

You will also need to get rid of time.sleep(1) since .sleep() is a blocking call, which means that it will block the tkinter mainloop which will cause your program to not respond.

Sign up to request clarification or add additional context in comments.

2 Comments

So i have to use event as a positional argument anytime i define a function in where there is a variable? And what if there's more than one? And also , could you suggest me a way to replace time.sleep()? Thanks for the help.
Your function has to except a positional argument since tkinter's event binding (when you wrote self.button1.bind("...", self.count)) automatically passes an event argument to the callback function, it doesn't have to be named event, it can be just this def count(self, _):. And for replacing time.sleep(), try searching for tkinter's root.after() method, if you're still having trouble, I can write a solution when I have the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.