停止连续函数的执行
Stopping the execution of a continuous function
在我的tkinter程序中,我打算有一个按钮来读取串口数据。
这将开始执行名为 readSerial() 的函数,该函数将获取数据并将其显示到文本框。
这是函数:
#this function reads the incoming data and inserts them into a text frame
def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
if vsb.get()[1]==1.0:
text.see("end")
root.after(100, readSerial)
我们通过按钮调用它。然后它开始连续执行,间隔时间 - 在 root.after(100, readSerial)
行
中指定
不过,我的串口设备(arduino)会有其他的操作模式。
所以我还有另一个按钮可以命令 arduino 停止说话。
由于 arduino 不会发送任何数据,我还必须停止执行 readSerial()。
可以吗?
可以使用 after_cancel(id)
函数停止 after()
函数调用。每次调用 after(...)
函数时,它都会 returns 一个可用于停止函数调用的后缀 ID。可以参考这个answer.
...
after_ids = {}
# this function reads the incoming data and inserts them into a text frame
def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
if vsb.get()[1] == 1.0:
text.see("end")
after_ids[1] = root.after(100, readSerial)
def stopSerial():
if after_ids.get(1) is not None:
root.after_cancel(after_ids[1])
...
在我的tkinter程序中,我打算有一个按钮来读取串口数据。 这将开始执行名为 readSerial() 的函数,该函数将获取数据并将其显示到文本框。
这是函数:
#this function reads the incoming data and inserts them into a text frame
def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
if vsb.get()[1]==1.0:
text.see("end")
root.after(100, readSerial)
我们通过按钮调用它。然后它开始连续执行,间隔时间 - 在 root.after(100, readSerial)
行
不过,我的串口设备(arduino)会有其他的操作模式。 所以我还有另一个按钮可以命令 arduino 停止说话。
由于 arduino 不会发送任何数据,我还必须停止执行 readSerial()。
可以吗?
可以使用 after_cancel(id)
函数停止 after()
函数调用。每次调用 after(...)
函数时,它都会 returns 一个可用于停止函数调用的后缀 ID。可以参考这个answer.
...
after_ids = {}
# this function reads the incoming data and inserts them into a text frame
def readSerial():
ser_bytes = ser.readline()
ser_bytes = ser_bytes.decode("utf-8")
text.insert("end", ser_bytes)
if vsb.get()[1] == 1.0:
text.see("end")
after_ids[1] = root.after(100, readSerial)
def stopSerial():
if after_ids.get(1) is not None:
root.after_cancel(after_ids[1])
...