# 导入 webview 用于前端通知 try: import webview except ImportError: webview = None def show_notification(message: str, message_type: str = "error"): """显示 pywebview 顶层通知(5秒后自动消失) Args: message: 通知消息 message_type: 消息类型 (success/warning/error/info) """ if webview and webview.windows: try: # 转义单引号,防止 JavaScript 语法错误 safe_message = message.replace("'", "\\'").replace('"', '\\"').replace('\n', '\\n') # 设置通知样式颜色 color_map = { 'success': '#67C23A', 'warning': '#E6A23C', 'error': '#F56C6C', 'info': '#909399' } bg_color = color_map.get(message_type, '#F56C6C') # 构建前端通知的 JavaScript 代码 - 创建原生 HTML 通知 js_code = f""" (function() {{ // 移除已存在的通知 var existingNotif = document.getElementById('pywebview-notification'); if (existingNotif) {{ existingNotif.remove(); }} // 创建通知容器 var notif = document.createElement('div'); notif.id = 'pywebview-notification'; notif.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); ' + 'background: {bg_color}; color: white; padding: 12px 20px; border-radius: 4px; ' + 'box-shadow: 0 2px 12px rgba(0,0,0,0.3); z-index: 99999; font-size: 14px; ' + 'max-width: 600px; word-wrap: break-word; display: flex; align-items: center; gap: 10px;'; // 添加消息内容 var msgSpan = document.createElement('span'); msgSpan.textContent = '{safe_message}'; notif.appendChild(msgSpan); // 添加关闭按钮 var closeBtn = document.createElement('span'); closeBtn.innerHTML = '×'; closeBtn.style.cssText = 'cursor: pointer; font-size: 18px; font-weight: bold; margin-left: 10px;'; closeBtn.onclick = function() {{ notif.remove(); }}; notif.appendChild(closeBtn); // 添加到页面 document.body.appendChild(notif); // 5秒后自动消失 setTimeout(function() {{ if (notif && notif.parentNode) {{ notif.style.transition = 'opacity 0.3s'; notif.style.opacity = '0'; setTimeout(function() {{ notif.remove(); }}, 300); }} }}, 5000); }})(); """ # 在第一个窗口中执行 JavaScript webview.windows[0].evaluate_js(js_code) except Exception as e: print(f"显示通知失败: {str(e)}")