简体   繁体   中英

Python: Update GUI After Instruction

I designed a program to solve Rubik's cubes, and now I'm building a GUI for it using PySide. My program generates a list of moves required to solve the cube, and then executes them one by one. I would like my program to show the status of the cube for a short period of time between each move.

Currently, I'm trying to use the time module to make the program wait between executing moves. Basically like this:

for move in algorithm:
    executeMove()
    updateDisplay()
    time.sleep(0.1)

I figured this method would work just fine. However, when I run the application, it looks like it's sleeping for the sum time of each of the sleep calls, then showing the end result of the algorithm. I would ideally like to make it show a move, sleep 0.1, show a move, sleep 0.1, etc.

Is the sleep function ideal for the type of behavior I'm trying to get? Should I be using something different entirely? Thank you for your suggestions.

It'd be good to see a little more code, but it looks like you're probably blocking the main Qt thread. To accomplish what you want to do, you will need to be multi-threaded and use pyQtSignal s to update the UI. Here's a (maybe buggy) template

class MainWindow(QtWidgets.QMainWindow):
    updateSignal = QtCore.pyqtSignal()
    def __init__(self, algorithm):
        super(MainWindow, self).__init__()
        self.algorithm = algorithm
        self.updateSignal.connect(self.updateDisplay)
        self.loopThread = None
        self.startMonitoring()
    def startMonitoring(self):
        self.loopThread = MonitorLoop(self.updateSignal.emit, self.algorithm)
        self.loopThread.start()
    def updateDisplay(self):
        """ Update the UI here"""
        pass


class MonitorLoop(QtCore.QThread):
    def __init__(self, signal, algorithm):
        super(MonitorLoop, self).__init__()
        self.signal = signal # needs to be a pyQtSignal if it will update the UI
        self.algorithm = algorithm
    def run(self):
        for move in self.algorithm:
            executeMove()
            self.signal()
            time.sleep(0.1)

If you are using Qt 4, you will need to substitute QtGui for QWidgets . Of course, I don't actually know what algorithm is, so your implementation will need to accomodate that.

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