简体   繁体   中英

How to translate Python console program (including while true loop) to PyQt?

I have a Python console program that I want to transfer to a GUI. I thought of using PyQt 5, but I'm open to alternatives.

The simplified console code looks like this:

while True:
   data = obtain_data_from_device(source)
   print(datatotext(data))

Now from what I understand, GUI code works different. But how do I continuously update a text box in PyQt using the obtain_data_from_device function which might take any time from 0.5 to 30 seconds?

A while loop can't do it, as it screws up the GUI, a timer doesn't work, as the duration is variable.

I'd appreciate any hints.

One option, since you already have a working program that writes to STDOUT, is to let the GUI program run the console program as a child process using QProcess .

The child will run asynchronously under control of the GUI program and the GUI program will receive the child's output via signals, ie non-blocking

You could try something like this:

import sys
import random
import time
import string

from PyQt5 import QtWidgets, QtCore


def obtain_data_from_device(source):
    time.sleep(0.001)
    data = ''.join(random.choice(string.ascii_uppercase + string.digits)
                   for _ in range(len(source)))
    return data


class Main(QtWidgets.QMainWindow):

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.init_ui()

    def init_ui(self):

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.time)
        self.timer.start(0)

        self.lcd = QtWidgets.QLineEdit(self)
        self.lcd.setText(
            obtain_data_from_device("whatever data you're capturing"))

        self.setCentralWidget(self.lcd)

        self.setGeometry(300, 300, 250, 100)
        self.setWindowTitle("Displaying capture data from device")

    def time(self):
        self.lcd.setText(
            obtain_data_from_device("whatever data you're capturing"))


def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

You will just need to replace the existing obtain_data_from_device by yours.

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