0
votes

I am trying to implement a button that continuously runs steps of my game. The button involves an infinite loop that runs my step function over and over until the button is released. Problem is it doesn't work. Instead it usually freezes or gives me

TypeError: <lambda>() takes 0 positional arguments but 1 was given

Here is the code:

def __init__(self, root):
    Frame.__init__(self, root)

    self.butt_released = False

    button3 = Button(self.but_frame, text='Step', width=15, command=lambda :self.step_funct())
    button3.pack(side='right')
    button4 = Button(self.but_frame, text='Run', width=15)
    button4.pack(side='right')
    button4.bind("<Button-1>", lambda :self.run_funct())
    button4.bind("<ButtonRelease-1>", lambda :self.butt_release())

def run_funct(self):
    while True:
        self.step_funct()
        time.sleep(1)
        if self.butt_released:
            break
    self.butt_released = False

def butt_release(self):
    self.butt_released = True

If anyone can help me fix this then that would be great.

2

2 Answers

1
votes

You need to use the root.after() function, so try:

def __init__(self, root):
    Frame.__init__(self, root)
    self.root = root
    self.butt_released = True

    button3 = Button(self.but_frame, text='Step', width=15, command=lambda :self.step_funct())
    button3.pack(side='right')
    button4 = Button(self.but_frame, text='Run', width=15)
    button4.pack(side='right')
    button4.bind("<Button-1>", self.butt_press)
    button4.bind("<ButtonRelease-1>", self.butt_release)

def butt_press(self, event):
    self.butt_released = False
    self.run_funct()

def run_funct(self):
    if not self.butt_released:
        self.step_funct()
        self.root.after(10, self.run_funct)

def butt_release(self, event):
    self.butt_released = True
1
votes

While Benjamin James Drury is completely right, and using time.sleep and creating an infinite loop while using Tkinter (except for the Tkinter mainloop) are very bad ideas, I would like to point out the specific cause of the error you posted.

Your error comes from the line

button4.bind("<Button-1>", lambda :self.run_funct())

The bind function passes the event object to the function given, but your lambda does not accept any arguments. To let lambda accept the event, without using it you can use

button4.bind("<Button-1>", lambda e :self.run_funct())

This accepts the event as e, but does not use it.

The same goes for the next line ofcourse