基于pywebview开发Windows桌面应用:实现启动全屏图片5秒显示
实现PyWebView全屏启动页(类似Easeus启动效果)
要实现类似Easeus的全屏启动图效果,我们可以通过先创建无框全屏的启动窗口,加载本地HTML展示图片,延迟5秒后自动关闭并启动主应用窗口。以下是整合原有逻辑的完整实现:
步骤说明
- 用无框全屏窗口展示启动图片,避免窗口边框干扰视觉效果
- 用本地HTML+CSS实现图片全屏自适应
- 通过定时器控制启动页显示时长,到点后切换到主应用
- 保留原有网络请求的异常处理逻辑
完整代码
import webview import requests import tkinter as tk import threading # 启动页HTML内容(内嵌图片,也可以换成本地路径) SPLASH_HTML = """ <!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; width: 100vw; height: 100vh; overflow: hidden; background-color: #000; display: flex; justify-content: center; align-items: center; } img { max-width: 100%; max-height: 100%; object-fit: contain; } </style> </head> <body> <!-- 替换成你的启动图片路径,这里假设图片和脚本同目录 --> <img src="splash.png" alt="启动页"> </body> </html> """ def close_splash_and_start_main(splash_window): """关闭启动窗口,启动主应用逻辑""" splash_window.destroy() # 原有网络请求逻辑 url = "http://127.0.0.1:81" timeout = 10 try: requests.get(url, timeout=timeout) webview.create_window('主应用', 'http://127.0.0.1:8000/', resizable=True) webview.start() except (requests.ConnectionError, requests.Timeout): # 异常时启动Tkinter窗口 window = tk.Tk() window.title("异常提示") greeting = tk.Label(text="无法连接到服务,请检查网络或服务状态") greeting.pack(padx=20, pady=20) window.mainloop() def main(): # 创建启动窗口:无框、全屏、加载启动页HTML splash_window = webview.create_window( '启动页', html=SPLASH_HTML, frameless=True, fullscreen=True, resizable=False ) # 设置5秒后关闭启动页并启动主应用 threading.Timer(5.0, close_splash_and_start_main, args=(splash_window,)).start() # 启动WebView服务(注意:start方法会阻塞,所以定时器要在start前设置) webview.start(gui='cef') # Windows下推荐用CEF内核,兼容性更好 if __name__ == '__main__': main()
关键细节说明
- 启动页HTML:用CSS确保图片在全屏窗口中居中显示,自适应窗口大小,背景设为黑色避免白边
- 窗口配置:
frameless=True移除窗口边框,fullscreen=True强制全屏,resizable=False禁止调整大小 - 定时器逻辑:用
threading.Timer实现延迟操作,避免阻塞WebView的主线程 - 内核选择:Windows环境下指定
gui='cef'(需要提前安装pywebview[cef]),比默认的WinForms内核更稳定 - 异常处理:保留原有逻辑,网络异常时自动切换到Tkinter提示窗口
注意事项
- 确保启动图片
splash.png和脚本在同一目录,或者修改HTML中的图片路径为绝对路径 - 安装依赖:如果用CEF内核,执行
pip install pywebview[cef],否则用默认内核执行pip install pywebview
内容的提问来源于stack exchange,提问作者Nana
相关产品推荐
相关产品推荐

