本文介绍了用PyQt5,实现两个窗口永远自动循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PyQt5,我想实现一个两个窗口,一个接一个地自动显示,而无需用户与任何窗口交互.像这样:

Using PyQt5, I want to implement a two windows displaying one after another automatically, without the user interacting with any window. Something like this:

While True:
    Show Window1
    wait 2 seconds
    Close Window1
    Show Window2
    wait 2 seconds
    Close Window2

我遇到的问题是主UI线程卡在app.exec_()函数中,无法实现开启关闭逻辑.

The problem I am having is that the main UI thread is stuck in app.exec_() function, so it cannot implement the opening and closing logic.

import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic


class Win1(QMainWindow):
    def __init__(self):
        super(Win1, self).__init__()
        uic.loadUi('win1.ui', self)
        self.show()

class Win2(QMainWindow):
    def __init__(self):
        super(Win2, self).__init__()
        uic.loadUi('win2.ui', self)
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)

    while True:
        win = Win1()
        time.sleep(1)
        win.close()

        win = Win2()
        time.sleep(1)
        win.close()

        app.exec_() # <--------- Program blocks here

如果有人可以在不阻塞的情况下分享此工作的最小示例,我将不胜感激.或者请指出应该使用的机制.

I would appreciate if someone can share a minimal example for this working without blocking. Or please point to the mechanism that should be used.

推荐答案

如果您打算使用 Qt,那么您应该忘记顺序逻辑,但您必须使用事件来实现逻辑.例如,在您的情况下,您希望每次 T 都显示一个窗口,而隐藏另一个窗口,以便可以使用 QTimer 和一个标志来实现:

If you are going to work with Qt then you should forget about sequential logic but you have to implement the logic using events. For example, in your case you want one window to be shown every time T and another to be hidden, so that can be implemented with a QTimer and a flag:

import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic


class Win1(QMainWindow):
    def __init__(self):
        super(Win1, self).__init__()
        uic.loadUi('win1.ui', self)
        self.show()


class Win2(QMainWindow):
    def __init__(self):
        super(Win2, self).__init__()
        uic.loadUi('win2.ui', self)
        self.show()


if __name__ == "__main__":

    app = QApplication(sys.argv)

    timer = QTimer()
    timer.setProperty("flag", True)

    win1 = Win1()
    win2 = Win2()

    def on_timeout():
        flag = timer.property("flag")
        if flag:
            win1.show()
            win2.close()
        else:
            win2.show()
            win1.close()
        timer.setProperty("flag", not flag)

    timer.timeout.connect(on_timeout)
    timer.start(1 * 1000)
    on_timeout()

    app.exec_()

您不应该使用 while 循环或 time.sleep,因为它们会阻塞 GUI 所在的事件循环,即:它们会冻结窗口

You should not use while loop or time.sleep since they block the eventloop in which the GUI lives, that is: they freeze the windows

这篇关于用PyQt5,实现两个窗口永远自动循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 06:58