You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python PyQt5 打开窗口后如何实现10秒自动关闭功能

失效原因

你用time.sleep()的方案不生效,是因为PyQt的所有UI渲染、逻辑触发都依赖app.exec_()启动的主事件循环。time.sleep()会直接阻塞当前线程,导致事件循环无法正常启动运行,窗口不会渲染,后续的关闭逻辑也不会生效。

正确实现方案

PyQt内置的QTimer类可以实现不阻塞事件循环的异步延时操作,修改步骤如下:

  • 先导入QTimer模块
  • 在窗口显示后,调用QTimer.singleShot()设置10秒延时触发窗口关闭逻辑

修改后的完整代码:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTimer
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()
    # 设置10秒(10000毫秒)后自动关闭窗口
    QTimer.singleShot(10000, win.close)
    sys.exit(app.exec_())
    
window()

QTimer.singleShot()是单次触发的定时器,会在指定的毫秒数后异步调用绑定的目标函数,全程不会阻塞主事件循环,UI可以正常渲染交互,到时间就会自动执行关闭逻辑。

内容的提问来源于stack exchange,提问作者champagnepapi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:54:00