简体   繁体   English

如何将Python控制台程序(包括while true循环)转换为PyQt?

[英]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. 我有一个要转移到GUI的Python控制台程序。 I thought of using PyQt 5, but I'm open to alternatives. 我曾考虑使用PyQt 5,但我愿意接受其他选择。

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. 现在,据我了解,GUI代码的工作原理有所不同。 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? 但是,如何使用get_data_from_device函数连续更新PyQt中的文本框,这可能需要0.5到30秒的时间?

A while loop can't do it, as it screws up the GUI, a timer doesn't work, as the duration is variable. while循环无法做到,因为它搞砸了GUI,由于持续时间是可变的,所以计时器不起作用。

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 . 一种选择是,因为您已经具有可写入STDOUT的工作程序,所以可以让GUI程序使用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 子进程将在GUI程序的控制下异步运行,并且GUI程序将通过信号(即非阻塞)接收子进程的输出

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. 您只需要用自己的设备替换现有的gain_data_from_device。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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