tkinter使用一个带参数的回调函数来选择要做什么



我写了一个代码,执行一个函数在循环中,而按钮保持和停止执行时,按钮被释放。见下文.

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'x02x56x81x80x80x80x80x80x39x35x04')

现在,只要sch_plus_callback函数基本上总是做同样的事情,独立的命令我要按下,唯一改变的是ser.write中的字符串(必须根据我按下的按钮而改变)我想知道是否有一种方法可以发送像self.sch_plus_button.bind('<Button-1>', self.sch_plus_callback("button_1"))这样的参数,然后在我的sch_plus_callback中获得参数,如

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]))

我已经尝试了下面的代码,但是,因为我的代码是如何编写的,它触发RecursionError: maximum recursion depth exceeded,所以我不知道如何解决这个问题

我找到了一个解决方案

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

其中args[0]是表示按下按钮的参数,args[1]是要处理的事件

最新更新