Skip to main content
 首页 » 编程设计

python之cef python之调整大小时卡住

2025年02月15日7zhenyulu

今天我正在尝试使用 cefpython 开发一个 UI,它允许我嵌入一个 web 浏览器并通过 javascript 绑定(bind)与其交互。

我正在使用它在 Windows 平台上进行开发。 为此,我使用了“multi_threaded_message_loop”标志,它可以提高性能。 我还在 python 3 上使用 wxpython 来嵌入它。

问题是当我调整窗口大小时,使用 WindowUtils.OnSize() 会卡住我的应用程序。 99% 的时间,它发生在浏览器加载时(但它也发生在它完成时(很少))。

这里是重现的示例代码:

import platform 
import sys 
 
import wx 
from cefpython3 import cefpython 
 
WindowUtils = cefpython.WindowUtils() 
 
WIDTH = 800 
HEIGHT = 600 
 
import os 
 
class MainFrame(wx.Frame): 
    browser = None 
    mainPanel = None 
 
    def createMainBrowser(self): 
        self.browser = self.createBrowser(self.mainPanel) 
 
    def createBrowser(self, parent): 
        browser = cefpython.CreateBrowserSync( 
            self.getWindowInfo(parent), 
            browserSettings={}, 
            navigateUrl='http://www.google.com' 
        ) 
        return browser 
 
    def getWindowInfo(self, parent): 
        windowInfo = cefpython.WindowInfo() 
        windowInfo.SetAsChild(parent.GetHandle(), [0, 0, WIDTH, HEIGHT]) 
        return windowInfo 
 
    def __init__(self): 
        wx.Frame.__init__( 
            self, parent=None, id=wx.ID_ANY, title='wx', size=(WIDTH, HEIGHT) 
        ) 
        self.mainPanel = wx.Panel(self) 
        self.mainPanel.SetBackgroundColour(wx.GREEN) 
 
        cefpython.PostTask(cefpython.TID_UI, self.createMainBrowser) 
 
        self.mainPanel.Bind(wx.EVT_SIZE, self.OnSize) 
 
    def OnSize(self, _): 
        if not self.browser: 
            return 
 
        WindowUtils.OnSize(self.mainPanel.GetHandle(), 0, 0, 0) 
        self.browser.NotifyMoveOrResizeStarted() 
 
 
class App(wx.App): 
    def OnInit(self): 
        frame = MainFrame() 
        frame.Show() 
        return True 
 
if __name__ == '__main__': 
    sys.excepthook = cefpython.ExceptHook  # To shutdown all CEF processes on error 
    cefpython.Initialize({ 
        "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", 
        "browser_subprocess_path": cefpython.GetModuleDirectory() + "/subprocess", 
        "auto_zooming": "system_dpi", 
        "multi_threaded_message_loop": True, 
    }) 
    app = App(False) 
    app.MainLoop() 
    cefpython.Shutdown() 

非常感谢您的帮助!

阿兰

请您参考如下方法:

问题解决了! 而不是使用

def OnSize(self, _): 
    if not self.browser: 
        return 
 
    WindowUtils.OnSize(self.mainPanel.GetHandle(), 0, 0, 0) 
    self.browser.NotifyMoveOrResizeStarted() 

我用

def OnSize(self, sizeEvent): 
    if not self.browser: 
        return 
 
    w = sizeEvent.GetSize().GetWidth() 
    h = sizeEvent.GetSize().GetHeight() 
    win32gui.SetWindowPos(self.browser.GetWindowHandle(), 0, 0, 0, w, h, 0) 
    self.browser.NotifyMoveOrResizeStarted() 

我不知道这是不是因为我使用的是 Windows 10,但也许 WindowsUtils 需要更新!