0

This is my code, how can I make the opened window to close automatically after 10s? I tried with the time.sleep(10) and then win.close() but it doesn't do anything.

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys

def window():
    app = QApplication(sys.argv)
    win = QMainWindow()
    win.setGeometry(200,200,300,300)
    win.setWindowTitle("test")

    label = QtWidgets.QLabel(win)
    label.setText("test")
    label.move(50,50)
    win.show()
    sys.exit(app.exec_())
    
window()
  • You cannot use `time.sleep` because it blocks the event loop. Note that you couldn't use it anyway in your code because adding it *before* the `app.exec_()` would prevent the window to properly show and draw its contents (which is what the event loop does), nor *after* because `app.exec_()` is blocking and does not return until the application is quit (usually, when the last window is closed). Add `QtCore.QTimer.singleShot(10000, win.close)` ***before*** `sys.exit(app.exec_())`. – musicamante Oct 01 '21 at 12:09
  • @musicamante Thank you very much, that worked. What would I have to add if I want to restart it automatically? Like start - wait 10s - close - wait 10s- start - wait 10s - close ... (because a loop doesnt seem to work) – champagnepapi Oct 01 '21 at 12:23
  • A loop doesn't work because QTimer.singleShot starts immediately. You could create a function that toggles the visibility: `def toggleWindow(win): win.setVisible(not win.isVisible())`, then create a timer that calls it: `timer = QtCore.QTimer(interval=10000, timeout=lambda: toggleWindow(win))` `timer.start()`. – musicamante Oct 01 '21 at 12:30

0 Answers0