0

In my tkinter program, i plan to have a button to read serial data. This will begin the execution of a function called readSerial() that will grab data and display them to a textbox.

This is the function:

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

And we're calling it from a button. Then it starts executing continuously, in intervals - specified in the root.after(100, readSerial) line

However, my serial device (arduino) will have other modes of operation. So i will also have another button that will command the arduino to stop talking.

Since the arduino will not send any data, i will have to also stop readSerial() from executing.

Is it possible to do so?

user1584421
  • 3,499
  • 11
  • 46
  • 86

1 Answers1

2

A after() function calls can be stopped with after_cancel(id) function. Every time a after(...) function is called it returns an after id that can be used to stop the function call. You can refer to this 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])

...
Saad
  • 3,340
  • 2
  • 10
  • 32