简体   繁体   中英

Python GUI call function repeatedly and have button Presses

I'm having this issue where my GUI program calls another class repeatedly (say 5 times a second), it calls class.Process(). I also have buttons that call class.Process() and the gentlemen who gave me the code for the class.Process() says that when I have the two operating at once (repeatedly calling and buttons) they could overlap and cause errors. Is there a way around this so I don't have a possible 'double-call' of Process()?

thread = threading.Thread(target=self.run,args=()) \
thread.daemon = True  \
thread.start()
    
def run(self):
    self.T.insert(END,'\n')
    self.T.insert(END,'\n')
    while True: 
        boolean = self.shutterclass.IsIdle()
        while not boolean:
            self.shutterclass.Process()
            message = self.shutterclass.GetStatusMsg()
            if message:
                self.T.insert(END,message)
                self.T2.insert(END,message)
            t.sleep(0.2)

The above code calls the function repeatedly and the below code is a sample of a button press.

def isclicked(self,FPress,HPress,QBPress,SPress,EPress,JDPress,JCPress):
    '''Function to tell if a button is pressed.'''
    if FPress == True:
        now = datetime.now()
        
        self.shutterclass.Process(command = 'FIRE')
        self.T.insert(END,"\n" + now.strftime("%H:%M:%S"))
        self.T.insert(END,'\n' + 'Command: FIRE')
        self.T2.insert(END,"\n" + now.strftime("%H:%M:%S"))
        self.T2.insert(END,'\n' + 'Command: FIRE')
        
        self.T.insert(END, "\n" + f"{self.shutterclass.GetStatusMsg()}")

You could make it so that instead of doing the call to Process in the while loop, you call the button press event instead. That way both user input and program call go through the button press method. Then if the button press method does not have any inherent state, you could possibly avoid any clashes due to instances of the button object.

From what I can tell, the thread automatically calls the shutterclass. Process when it is idle, I will assume that means the user is not having any input in that object? But then you call the process method, which will change it's status and so the while loop will evaluate to true. One way to fix this could be to put the isIdle status of the shutter class into a different memory object, which will implement a semaphore. That way the callers of that resource will have to queue up in order to modify it, thus making it less probably that they both access it simultaneously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM