tkinter 在按钮保持按下状态时执行功能并在释放时停止

tkinter executes function while the button stays pressed and stop when released

我是 tkinter 的新手,我正在寻找一个按钮,只要按下按钮,它就会循环执行一个函数;释放按钮后,功能将不再执行

我目前有一个 tk.Button(self, text="S+", command=sch_plus_callback)

def sch_plus_callback():
    self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')

现在我想要某种按钮

def sch_plus_callback():
    while button_is_pressed:
            self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')

有办法吗?

我的完整代码是

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

        tk.Tk.__init__(self, *args, **kwargs)
        # self.insert_lengh_text_label = tk.Label(self, text="Max Packet Length")
        self.sch_plus_button = tk.Button(self, text="S+", command=self.sch_plus_callback)
        self.sch_plus_button.pack()
       
    def sch_plus_callback(self):
        
        self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')

我现在正在使用这些方法,但它更像是一种解决方法,而不是实际的解决方案

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

def sch_plus_callback(self, *args,):
    global repeat
    try:
        repeat = self.after(300, self.sch_plus_callback, args[0])
    except:
        pass
    self.ser.reset_input_buffer()
    self.ser.reset_output_buffer()
    self.ser.write(b'\x02\x56\x81\x80\x80\x80\x80\x80\x39\x35\x04')

在函数中,使用widget.bind(event, handler) 方法捕获释放鼠标左键“ButtonRelease-1”的事件,从而中断循环。 https://python-course.eu/tkinter/events-and-binds-in-tkinter.php#:~:text=Events%20can%20be%20key%20presses,and%20methods%20to%20an%20event.&text=If%20the%20defined%20event%20occurs,called%20with%20an%20event%20object. 为了使循环不会阻塞 tkinter,您需要通过 after(time, callback) 运行 它。 Tkinter 循环 link https://tkdocs.com/tutorial/eventloop.html。 示例代码:

from tkinter import *

def sch_plus_callback(event):
    global repeat
    repeat = root.after(500, sch_plus_callback, event)
    text.insert(END, "Bye Bye.....\n")


def stop_callback(event):
    root.after_cancel(repeat)




root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....\n")
text.pack()
button = Button(root, text="S+")
button.pack()
button.bind('<Button-1>', sch_plus_callback)
button.bind('<ButtonRelease-1>', stop_callback)

root.mainloop()

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

def sch_plus_callback(self, event):
   
    try:
        self.repeat = self.after(300, self.sch_plus_callback, event)