wxpython + cef 是优秀的 WebView 组件

CEF 即 (Chromium Embedded Framework);cef 是优秀的 WebView 组件。

pip install wxpython==4.2
wxPython-4.2.0-cp37-cp37m-win_amd64.whl (18.0 MB)
Successfully installed wxpython-4.2.0

pip install cefpython3
cefpython3-66.1-py2.py3-none-win_amd64.whl (69.0 MB)
Successfully installed cefpython3-66.1

cd \Python37\Lib\site-packages\cefpython3\examples
copy wxpython.py  wx_cef.py
用的图片在 \Python37\Lib\site-packages\cefpython3\examples\resources\
编写 wx_cef.py  如下

# -*- coding: utf-8 -*-
# Example of embedding CEF Python browser using wxPython library.
# This example has a top menu and a browser widget without navigation bar.# Tested configurations:
# - wxPython 4.0 on Windows/Mac/Linux
# - wxPython 3.0 on Windows/Mac
# - wxPython 2.8 on Linux
# - CEF Python v66.0+import os
import sys
import platform
import wx
from cefpython3 import cefpython as cef# Platforms
WINDOWS = (platform.system() == "Windows")
LINUX = (platform.system() == "Linux")
MAC = (platform.system() == "Darwin")# Configuration
WIDTH = 1000
HEIGHT = 600# Globals
g_count_windows = 0
baseurl = "http://localhost:8888/"def main():check_versions()sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on errorsettings = {}if MAC:# Issue #442 requires enabling message pump on Mac# and calling message loop work in a timer both at# the same time. This is an incorrect approach# and only a temporary fix.settings["external_message_pump"] = Trueif WINDOWS: pass# noinspection PyUnresolvedReferences, PyArgumentList#cef.DpiAware.EnableHighDpiSupport()cef.Initialize(settings=settings)app = CefApp(False)app.MainLoop()del app  # Must destroy before calling Shutdownif not MAC:# On Mac shutdown is called in OnClosecef.Shutdown()def check_versions():print("[wx_cef.py] CEF Python {ver}".format(ver=cef.__version__))print("[wx_cef.py] Python {ver} {arch}".format(ver=platform.python_version(), arch=platform.architecture()[0]))print("[wx_cef.py] wxPython {ver}".format(ver=wx.version()))# CEF Python version requirementassert cef.__version__ >= "66.0", "CEF Python v66.0+ required to run this"def scale_window_size_for_high_dpi(width, height):"""Scale window size for high DPI devices. This func can becalled on all operating systems, but scales only for Windows.If scaled value is bigger than the work area on the displaythen it will be reduced."""if not WINDOWS:return width, height(_, _, max_width, max_height) = wx.GetClientDisplayRect().Get()# noinspection PyUnresolvedReferences(width, height) = cef.DpiAware.Scale((width, height))if width > max_width:width = max_widthif height > max_height:height = max_heightreturn width, heightclass MainFrame(wx.Frame):def __init__(self):self.browser = None# Must ignore X11 errors like 'BadWindow' and others by# installing X11 error handlers. This must be done after# wx was intialized.if LINUX:cef.WindowUtils.InstallX11ErrorHandlers()global g_count_windowsg_count_windows += 1if WINDOWS:# noinspection PyUnresolvedReferences, PyArgumentListprint("[wx_cef.py] System DPI settings: %s"% str(cef.DpiAware.GetSystemDpi()))if hasattr(wx, "GetDisplayPPI"):print("[wx_cef.py] wx.GetDisplayPPI = %s" % wx.GetDisplayPPI())print("[wx_cef.py] wx.GetDisplaySize = %s" % wx.GetDisplaySize())print("[wx_cef.py] MainFrame declared size: %s"% str((WIDTH, HEIGHT)))size = scale_window_size_for_high_dpi(WIDTH, HEIGHT)print("[wx_cef.py] MainFrame DPI scaled size: %s" % str(size))wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,title='wxPython + cef', size=size)# wxPython will set a smaller size when it is bigger# than desktop size.print("[wx_cef.py] MainFrame actual size: %s" % self.GetSize())self.setup_icon()self.create_menu()self.Bind(wx.EVT_CLOSE, self.OnClose)# Set wx.WANTS_CHARS style for the keyboard to work.# This style also needs to be set for all parent controls.self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS)self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize)if MAC:# Make the content view for the window have a layer.# This will make all sub-views have layers. This is# necessary to ensure correct layer ordering of all# child views and their layers. This fixes Window# glitchiness during initial loading on Mac (Issue #371).NSApp.windows()[0].contentView().setWantsLayer_(True)if LINUX:# On Linux must show before embedding browser, so that handle# is available (Issue #347).self.Show()# In wxPython 3.0 and wxPython 4.0 on Linux handle is# still not yet available, so must delay embedding browser# (Issue #349).if wx.version().startswith("3.") or wx.version().startswith("4."):wx.CallLater(100, self.embed_browser)else:# This works fine in wxPython 2.8 on Linuxself.embed_browser()else:self.embed_browser()self.Show()def setup_icon(self):icon_file = os.path.join(os.path.abspath(os.path.dirname(__file__)),"resources", "wxpython.png")# wx.IconFromBitmap is not available on Linux in wxPython 3.0/4.0if os.path.exists(icon_file) and hasattr(wx, "IconFromBitmap"):icon = wx.IconFromBitmap(wx.Bitmap(icon_file, wx.BITMAP_TYPE_PNG))self.SetIcon(icon)def create_menu(self):filemenu = wx.Menu()filemenu.Append(1, "Open Url")filemenu.Append(2, "Go Back")menubar = wx.MenuBar()menubar.Append(filemenu, "&File")self.SetMenuBar(menubar)self.Bind(wx.EVT_MENU, self.OnOpenUrl, id=1)self.Bind(wx.EVT_MENU, self.OnGoBack, id=2)def embed_browser(self):window_info = cef.WindowInfo()(width, height) = self.browser_panel.GetClientSize().Get()assert self.browser_panel.GetHandle(), "Window handle not available"window_info.SetAsChild(self.browser_panel.GetHandle(),[0,0,width,height])self.browser = cef.CreateBrowserSync(window_info, url=baseurl)self.browser.SetClientHandler(FocusHandler())def OnOpenUrl(self, event):dlg = wx.TextEntryDialog(self, "Open Location","Enter a full URL or local path","http://", wx.OK|wx.CANCEL)dlg.CentreOnParent()global baseurlif dlg.ShowModal() == wx.ID_OK:baseurl = dlg.GetValue()self.browser.LoadUrl(baseurl)dlg.Destroy()def OnGoBack(self, event):if self.browser:self.browser.GoBack()def OnSetFocus(self, _):if not self.browser:returnif WINDOWS:cef.WindowUtils.OnSetFocus(self.browser_panel.GetHandle(), 0,0,0)self.browser.SetFocus(True)def OnSize(self, _):if not self.browser:returnif WINDOWS:cef.WindowUtils.OnSize(self.browser_panel.GetHandle(), 0,0,0)elif LINUX:(x, y) = (0, 0)(width, height) = self.browser_panel.GetSize().Get()self.browser.SetBounds(x, y, width, height)self.browser.NotifyMoveOrResizeStarted()def OnClose(self, event):print("[wx_cef.py] OnClose called")if not self.browser:# May already be closing, may be called multiple times on Macreturnif MAC:# On Mac things work differently, other steps are requiredself.browser.CloseBrowser()self.clear_browser_references()self.Destroy()global g_count_windowsg_count_windows -= 1if g_count_windows == 0:cef.Shutdown()wx.GetApp().ExitMainLoop()# Call _exit otherwise app exits with code 255 (Issue #162).# noinspection PyProtectedMemberos._exit(0)else:# Calling browser.CloseBrowser() and/or self.Destroy()# in OnClose may cause app crash on some paltforms in# some use cases, details in Issue #107.self.browser.ParentWindowWillClose()event.Skip()self.clear_browser_references()def clear_browser_references(self):# Clear browser references that you keep anywhere in your# code. All references must be cleared for CEF to shutdown cleanly.self.browser = Noneclass FocusHandler(object):def OnGotFocus(self, browser, **_):# Temporary fix for focus issues on Linux (Issue #284).if LINUX:print("[wx_cef.py] FocusHandler.OnGotFocus:"" keyboard focus fix (Issue #284)")browser.SetFocus(True)class CefApp(wx.App):def __init__(self, redirect):self.timer = Noneself.timer_id = 1self.is_initialized = Falsesuper(CefApp, self).__init__(redirect=redirect)def OnPreInit(self):super(CefApp, self).OnPreInit()# On Mac with wxPython 4.0 the OnInit() event never gets# called. Doing wx window creation in OnPreInit() seems to# resolve the problem (Issue #350).if MAC and wx.version().startswith("4."):print("[wx_cef.py] OnPreInit: initialize here"" (wxPython 4.0 fix)")self.initialize()def OnInit(self):self.initialize()return Truedef initialize(self):if self.is_initialized:returnself.is_initialized = Trueself.create_timer()frame = MainFrame()self.SetTopWindow(frame)frame.Show(True)def create_timer(self):# See also "Making a render loop":# http://wiki.wxwidgets.org/Making_a_render_loop# Another way would be to use EVT_IDLE in MainFrame.self.timer = wx.Timer(self, self.timer_id)self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)self.timer.Start(10)  # 10ms timerdef on_timer(self, _):cef.MessageLoopWork()def OnExit(self):self.timer.Stop()return 0if __name__ == '__main__':main()

运行 python wx_cef.py

我注释了 #cef.DpiAware.EnableHighDpiSupport() ,以避免cef 刷新不完善时造成显示重影。

web 服务程序参见: python:mdict + bottle = web 查询英汉词典

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/55895.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode笔记:Weekly Contest 360

LeetCode笔记:Weekly Contest 360 0. 吐槽1. 题目一 1. 解题思路2. 代码实现 2. 题目二 1. 解题思路2. 代码实现 3. 题目三 1. 解题思路2. 代码实现 4. 题目四 1. 解题思路2. 代码实现 比赛链接:https://leetcode.com/contest/weekly-contest-360/ 0.…

C++学习记录——이십팔 C++11(4)

文章目录 包装器1、functional2、绑定 这一篇比较简短,只是因为后要写异常和智能指针,所以就把它单独放在了一篇博客,后面新开几篇博客来写异常和智能指针 包装器 1、functional 包装器是一个类模板,对可调用对象类型进行再封装…

江西抚州新能源汽车3d扫描零部件逆向抄数测量改装-CASAIM中科广电

汽车改装除了在外观方面越来越受到消费者的青睐,在性能和实用性提升上面的需求也是日趋增多,能快速有效地对客户指定汽车零部件进行一个改装,是每一个汽车改装企业和工程师的追求,也是未来消费者个性化差异化的要求。下面CASAIM中…

Fei-Fei Li-Lecture 16:3D Vision 【斯坦福大学李飞飞CV课程第16讲:3D Vision】

目录 P1 2D Detection and Segmentation​编辑 P2 Video 2D time series P3 Focus on Two Problems P4 Many more topics in 3D Vision P5-10 Multi-View CNN P11 Experiments – Classification & Retrieval P12 3D Shape Representations P13--17 3D Shape Rep…

好用的可视化大屏适配方案

1、scale方案 优点&#xff1a;使用scale适配是最快且有效的&#xff08;等比缩放&#xff09; 缺点&#xff1a; 等比缩放时&#xff0c;项目的上下或者左右是肯定会有留白的 实现步骤 <div className"screen-wrapper"><div className"screen"…

同源策略以及SpringBoot的常见跨域配置

先说明一个坑。在跨域的情况下&#xff0c;浏览器针对复杂请求&#xff0c;会发起预检OPTIONS请求。如果服务端对OPTIONS进行拦截&#xff0c;并返回非200的http状态码。浏览器一律提示为cors error。 一、了解跨域 1.1 同源策略 浏览器的同源策略&#xff08;Same-Origin Po…

06.sqlite3学习——DQL(数据查询)(全)

目录 SQLite——DQL&#xff08;数据查询&#xff09; 数据集 select语句 条件查询 比较 确定范围 确定集合 like 查询记录 查询不重复的记录 排序和限制 排序 限制 聚合 聚合函数 语法 SQLite Group By详解 语法 实例 SQLite Having 子句 语法 实例 多…

[JavaWeb]【十一】web后端开发-SpringBootWeb案例(登录)

目录 一、登录功能 1.1 思路 1.2 LoginController 1.3 EmpService 1.4 EmpServiceImpl 1.5 EmpMapper 1.6 启动服务-测试 1.7 前后端联调 二、登录校验&#xff08;重点&#xff09; 2.1 问题 2.2 问题分析 2.3 登录校验​编辑 2.4 会话技术 2.4.1 会话技术 2.4.2 …

QT使用QXlsx实现Excel图片与图表操作 QT基础入门【Excel的操作】

构建图表数据 /// 构建图表数据for (int i = 1; i < 10; ++i) {mxlsx.write(i, 1, i * i * i); // A1:A9mxlsx.write(i, 2, i * i); // B1:B9mxlsx.write(i, 3, i * i - 1); // C1:C9} 需要包含头文件 #include "xlsxchart.h" 1. 饼状图 Chart *pieChart = mxlsx.…

hive可以删除单条数据吗

参考&#xff1a; hive只操作几条数据特别慢 hive可以删除单条数据吗_柳随风的技术博客_51CTO博客

SpringBoot权限认证

SpringBoot的安全 常用框架&#xff1a;Shrio,SpringSecurity 两个功能&#xff1a; Authentication 认证Authorization 授权 权限&#xff1a; 功能权限访问权限菜单权限 原来用拦截器、过滤器来做&#xff0c;代码较多。现在用框架。 SpringSecurity 只要引入就可以使…

2023年6月GESP C++ 三级试卷解析

2023年6月GESP C 三级试卷解析 一、单选题&#xff08;每题2分&#xff0c;共30分&#xff09; 1.高级语言编写的程序需要经过以下&#xff08; &#xff09;操作&#xff0c;可以生成在计算机上运行的可执行代码。 A.编辑 B.保存 C.调试 D.编译 【答案】D 【考纲知识点…

FPGA GTX全网最细讲解,aurora 8b/10b协议,OV5640板对板视频传输,提供2套工程源码和技术支持

目录 1、前言免责声明 2、我这里已有的 GT 高速接口解决方案3、GTX 全网最细解读GTX 基本结构GTX 发送和接收处理流程GTX 的参考时钟GTX 发送接口GTX 接收接口GTX IP核调用和使用 4、设计思路框架视频源选择OV5640摄像头配置及采集动态彩条视频数据组包GTX aurora 8b/10b数据对…

最新域名和子域名信息收集技术

域名信息收集 1&#xff0e;WHOIS查询 WHOIS是一个标准的互联网协议&#xff0c;可用于收集网络注册信息、注册域名﹑IP地址等信息。简单来说&#xff0c;WHOIS就是一个用于查询域名是否已被注册及注册域名详细信息的数据库&#xff08;如域名所有人、域名注册商&#xff09;…

什么是MVC模式?描述每个组件的作用?解释关系型数据库和非关系型数据库的区别?

1、什么是MVC模式&#xff1f;描述每个组件的作用。 MVC模式&#xff08;Model-View-Controller&#xff09;是一种常见的软件设计模式&#xff0c;用于将应用程序的逻辑、用户界面和数据分离为三个组件。 MVC模式中的三个组件如下&#xff1a; Model&#xff08;模型&#…

pytorch下的scatter、sparse安装

知道自己下载的torch配置 import torch print(torch.__version__) print(torch.version.cuda)进入网站&#xff0c;选择自己配置 https://pytorch-geometric.com/whl/下载相应的包 安装 pip install ******.whl

【音视频】 视频的播放和暂停,当播放到末尾时触发 ended 事件,循环播放,播放速度

video 也可以 播放 MP3 音频&#xff0c;当不想让 视频显示出来的话&#xff0c;可以 给 video 设置宽和高 1rpx &#xff0c;不可以隐藏 <template><view class"form2box"><u-navbar leftClick"leftClick"><view slot"left&q…

Qt 查找文件夹下指定类型的文件及删除特定文件

一 查找文件 bool MyXML::findFolderFileNames() {//指定文件夹名QDir dir("xml");if(!dir.exists()){qDebug()<<"folder does not exist!";return false;}//指定文件后缀名&#xff0c;可指定多种类型QStringList filter("*.xml");//指定…

Uniapp笔记(八)初识微信小程序

一、微信小程序基本介绍 1、什么是微信小程序 微信小程序简称小程序&#xff0c;英文名Mini Program&#xff0c;是一种不需要下载安装即可使用的应用&#xff0c;它实现了应用“触手可及”的梦想&#xff0c;用户扫一扫或搜一下即可打开应用 小程序是一种新的开放能力&#…

04_21 slab分配器 分配对象实战

目的 ( slab块分配器分配内存)&#xff0c;编写个内核模块&#xff0c;创建名称为 “mycaches"的slab描述符&#xff0c;小为40字节, align为8字节&#xff0c; flags为0。 从这个slab描述符中分配个空闲对象。 代码大概 内核模块中 #include <linux/version.h>…