Home > Blockchain >  tkinter uses single function callback with arguments to chose what to do
tkinter uses single function callback with arguments to chose what to do

Time:05-16

I've written a code that execute a function in loop while a button is hold and stop the execution when the button is released. See below.

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        
        self.sch_plus_button = tk.Button(self, text="S ", command=self.sch_plus_callback)
        self.sch_plus_button.pack()
        self.sch_plus_button.bind('<Button-1>', self.sch_plus_callback)
        self.sch_plus_button.bind('<ButtonRelease-1>', self.button_stop_callback)

    def button_stop_callback(self, event):
        self.after_cancel(repeat)

    def sch_plus_callback(self, *args):
        global repeat
        try:
            # TODO find right time to send data to keep RELE ON
            repeat = self.after(200, self.sch_plus_callback, args[0])
        except IndexError:
            pass
        self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')

Now, as soon as the sch_plus_callback function basically do always the same stuff, indipendently by the command I'm gonna press, and the only thing that changes is the string in ser.write (which have to change accoridngly to the button I'm pushing) I would like to know if there's a way to send an argument like self.sch_plus_button.bind('<Button-1>', self.sch_plus_callback("button_1")) and then get the argument inside my sch_plus_callback like

def sch_plus_callback(self, *args):
            global repeat
            try:
                # TODO find right time to send data to keep RELE ON
                repeat = self.after(200, self.sch_plus_callback(args[0]), args[1])
            except IndexError:
                pass
            self.ser.write(string_to_send(args[0]))

I've tried the code below but, because how my code is written, it triggers RecursionError: maximum recursion depth exceeded so I've no idea on how workaround the issue

CodePudding user response:

A solution I found has been

        self.sch_plus_button = tk.Button(self, text="S ", command=lambda: self.sch_plus_callback('sch_plus'))
        self.sch_plus_button.pack()
        self.sch_plus_button.bind('<Button-1>', lambda event: self.sch_plus_callback('sch_plus', event))
        self.sch_plus_button.bind('<ButtonRelease-1>', self.button_stop_callback)

    def button_stop_callback(self, event):
        self.after_cancel(repeat)

    def sch_plus_callback(self, *args):
        global repeat
        logging.info("args are "   str(args))

        try:
            repeat = self.after(300, self.sch_plus_callback, args[0], args[1])
        except IndexError:
            pass

Where args[0] is the argument that indicates the button pressed and args[1] the event to hendle

  • Related