Files
deskflow/app.py
2026-04-09 10:37:51 +08:00

61 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 关键确保Windows安装了WebView2运行时pywebview2必需
# 下载地址https://developer.microsoft.com/zh-CN/microsoft-edge/webview2/#download-section
import sys,os,time
import threading
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
'''定义供 JS 调用的 Python 函数'''
class Api:
"""暴露给 JS 的 Python 接口类(所有方法都会被 JS 访问)"""
def __init__(self):
self.window = None # 保存窗口实例,用于 Python 主动调用 JS
def set_window(self, window):
"""初始化时绑定窗口实例"""
self.window = window
def python_close_window(self):
"""JS 调用关闭窗口"""
print("[Python] 收到关闭窗口请求")
self.window.destroy()
'''Python 主动调用 JS 函数'''
def python_call_js_periodically(window):
"""Python 定时调用 JS 函数(模拟主动推送数据)"""
count = 0
while window:
count += 1
# 执行 JS 函数,传递参数
window.evaluate_js(f'js_receive_python_msg("Python主动推送:第{count}条消息")')
time.sleep(3) # 每 3 秒推送一次
if count >= 5:break
import webview
if __name__ == '__main__':
api = Api()
window = webview.create_window(
title='PyWebView', # 窗口标题
url=f"file:///{CURRENT_DIR}/app.html",
resizable=True, # 是否允许调整窗口大小(默认 True
transparent=True,
# frameless=True,
# easy_drag=True, # 窗口无边框
js_api=api
)
# 绑定窗口实例到 API供异步任务调用 JS
api.set_window(window)
threading.Thread(target=python_call_js_periodically, args=(window,), daemon=True).start()
webview.start(
private_mode=False, # WebRTC必需关闭私有模式
# debug=True,
http_server=True
)