如何使用Python实现无窗口显示文本或PNG图片且可正常关闭
无独立窗口显示文本/PNG图片的实现方案
通过PyQt5创建无边框透明窗口模拟直接显示在桌面的效果,支持正常关闭,不存在原有Tk方案需要手动杀进程的问题,同时支持点击穿透、自定义显示时长、快捷键关闭等功能。
依赖安装
- 安装所需依赖:
pip install pyqt5
完整实现代码
显示文本版本
import sys from PyQt5.QtWidgets import QApplication, QLabel, QWidget from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QFont class DesktopDisplay(QWidget): def __init__(self, text, display_time=None): super().__init__() # 窗口核心属性配置 self.setWindowFlags( Qt.FramelessWindowHint | # 去掉边框 Qt.WindowStaysOnTopHint | # 窗口置顶 Qt.Tool | # 任务栏不显示图标 Qt.WindowTransparentForInput # 可选:开启后点击穿透到桌面 ) self.setAttribute(Qt.WA_TranslucentBackground) # 背景透明 # 文本标签配置 self.label = QLabel(self) self.label.setText(text) self.label.setFont(QFont("微软雅黑", 20, QFont.Bold)) self.label.setStyleSheet("color: red;") # 自定义文本颜色 self.adjustSize() # 窗口位置:可以自定义坐标,这里默认放屏幕左上角 self.move(50, 50) # 自动关闭配置,display_time单位为毫秒 if display_time: QTimer.singleShot(display_time, self.close) def keyPressEvent(self, event): # 按ESC键手动关闭 if event.key() == Qt.Key_Escape: self.close() if __name__ == "__main__": app = QApplication(sys.argv) # 示例:显示文本"测试内容",5秒后自动关闭,不需要自动关闭就不传第二个参数 window = DesktopDisplay("测试内容", 5000) window.show() sys.exit(app.exec_())
显示PNG图片版本
import sys from PyQt5.QtWidgets import QApplication, QLabel, QWidget from PyQt5.QtCore import Qt, QTimer from PyQt5.QtGui import QPixmap class DesktopDisplay(QWidget): def __init__(self, img_path, display_time=None): super().__init__() # 窗口核心属性配置 self.setWindowFlags( Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool | Qt.WindowTransparentForInput ) self.setAttribute(Qt.WA_TranslucentBackground) # 图片加载配置 self.label = QLabel(self) pixmap = QPixmap(img_path) self.label.setPixmap(pixmap) self.adjustSize() # 自定义窗口显示位置 self.move(100, 100) if display_time: QTimer.singleShot(display_time, self.close) def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.close() if __name__ == "__main__": app = QApplication(sys.argv) # 示例:显示本地test.png图片,10秒后自动关闭 window = DesktopDisplay("test.png", 10000) window.show() sys.exit(app.exec_())
关键配置说明
- 如果不需要点击穿透,删除
Qt.WindowTransparentForInput参数即可,保留后可以拖拽、点击窗口内容 - 可以通过修改
move()方法的参数调整内容显示的屏幕坐标 - 文本样式、字体、颜色都可以通过修改
setStyleSheet内容自定义 - 不需要自动关闭功能的话,实例化类时不传第二个
display_time参数即可,随时按ESC键关闭窗口
内容的提问来源于stack exchange,提问作者mdtrong1305
相关产品推荐
相关产品推荐

