Interrupt a while loop when pressing down a stop button in GUI (python)

358 Views Asked by At

Currently I am working on a GUI that has two buttons: START and STOP. The idea is that when the user presses down START the code will print everything the user is typing (real time) in a txt file, and once the STOP button is pressed the code will stop printing further typing. My question is: If I use a loop "while True" in the event when the button start is pressed, immediately the GUI is blocked, and therefore what the event of stop button is blocked (the codes goes into a endless loop)

self.close_signal=False

def Start(self,event):

    path=os.chdir(self.pathsave)
    with open(self.tFileName.GetValue()+".txt",'a') as f:

        #This is the cycle I need to break when the button bStop (event Stop)
        while True:
            char=self.getch()
            f.write(char)
            if self.close_signal==True:
                break

def Stop(self,event):
    self.close_signal=True
    f.close()


def getch(self):

    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)

    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd , termios.TCSADRAIN , old_settings)
    return ch

This piece of code is included in the class of my wx.Frame Thanks in advance!

0

There are 0 best solutions below