gpt4 book ai didi

python - 如何使用 CEFPython 在 Tkinter 窗口中添加 WebBrowser 小部件?

转载 作者:行者123 更新时间:2023-12-04 07:30:05 28 4
gpt4 key购买 nike

我想在我的 tkinter 应用程序中显示一个 WebBrowser。根据以下示例:

##############
# label #
#————————————#
# webbrowser #
##############
这是我尝试过的:
https://github.com/iCarlosCode/Problematika/blob/begining/calculator/cef3.py
我试图复制 cefpython 示例并使用 BrowserFrame,但它不起作用。 cefpython tkinter 示例:
https://github.com/cztomczak/cefpython/blob/master/examples/tkinter_.py
任何人都可以帮助我吗?

最佳答案

因此,您的主代码有两个核心问题:

  • 您没有初始化 cefpython
  • 您的 browser_frame未配置为适合整个区域

  • 简而言之,答案是:
    import tkinter as tk
    from tkinter import *
    from cefpython3 import cefpython as cef
    import ctypes

    def main():
    win = Tk()
    cef.Initialize()

    win.minsize(600,600)
    win.grid_columnconfigure(0, weight=1)
    win.grid_rowconfigure(0, weight=1)

    #Create Frame
    frame = Frame(win, bg='black')
    frame.grid(row=0, column=0, sticky=('NSWE'))

    # Create Browser Frame
    browser_frame = BrowserFrame(frame)
    browser_frame.pack(fill=tk.BOTH, expand=tk.YES)

    win.mainloop()
    cef.Shutdown()

    class BrowserFrame(tk.Frame):

    def __init__(self, mainframe, navigation_bar=None):
    self.navigation_bar = navigation_bar
    self.closing = False
    self.browser = None
    tk.Frame.__init__(self, mainframe)
    self.mainframe = mainframe
    self.bind("<FocusIn>", self.on_focus_in)
    self.bind("<FocusOut>", self.on_focus_out)
    self.bind("<Configure>", self.on_configure)
    """For focus problems see Issue #255 and Issue #535. """
    self.focus_set()

    #URLURLURL
    def embed_browser(self):
    window_info = cef.WindowInfo()
    rect = [0, 0, self.winfo_width(), self.winfo_height()]
    window_info.SetAsChild(self.get_window_handle(), rect)
    self.browser = cef.CreateBrowserSync(window_info,
    url="file:///calculo.html")
    assert self.browser
    #self.browser.SetClientHandler(LifespanHandler(self))
    #self.browser.SetClientHandler(LoadHandler(self))
    #self.browser.SetClientHandler(FocusHandler(self))
    self.message_loop_work()

    def get_window_handle(self):
    if self.winfo_id() > 0:
    return self.winfo_id()
    else:
    raise Exception("Couldn't obtain window handle")

    def message_loop_work(self):
    cef.MessageLoopWork()
    self.after(10, self.message_loop_work)

    def on_configure(self, _):
    if not self.browser:
    self.embed_browser()

    def on_root_configure(self):
    # Root <Configure> event will be called when top window is moved
    if self.browser:
    self.browser.NotifyMoveOrResizeStarted()

    def on_mainframe_configure(self, width, height):
    if self.browser:
    if WINDOWS:
    ctypes.windll.user32.SetWindowPos(
    self.browser.GetWindowHandle(), 0,
    0, 0, width, height, 0x0002)
    self.browser.NotifyMoveOrResizeStarted()

    def on_focus_in(self, _):
    #logger.debug("BrowserFrame.on_focus_in")
    if self.browser:
    self.browser.SetFocus(True)

    def on_focus_out(self, _):
    #logger.debug("BrowserFrame.on_focus_out")
    """For focus problems see Issue #255 and Issue #535. """
    pass

    def on_root_close(self):
    #logger.info("BrowserFrame.on_root_close")
    if self.browser:
    #logger.debug("CloseBrowser")
    self.browser.CloseBrowser(True)
    self.clear_browser_references()
    else:
    #logger.debug("tk.Frame.destroy")
    self.destroy()


    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 = None

    class LifespanHandler(object):

    def __init__(self, tkFrame):
    self.tkFrame = tkFrame

    def OnBeforeClose(self, browser, **_):
    #logger.debug("LifespanHandler.OnBeforeClose")
    self.tkFrame.quit()

    class LoadHandler(object):

    def __init__(self, browser_frame):
    self.browser_frame = browser_frame

    def OnLoadStart(self, browser, **_):
    if self.browser_frame.master.navigation_bar:
    self.browser_frame.master.navigation_bar.set_url(browser.GetUrl())


    class FocusHandler(object):
    """For focus problems see Issue #255 and Issue #535. """

    def __init__(self, browser_frame):
    self.browser_frame = browser_frame

    def OnTakeFocus(self, next_component, **_):
    pass#logger.debug("FocusHandler.OnTakeFocus, next={next}".format(next=next_component))

    def OnSetFocus(self, source, **_):
    return True

    def OnGotFocus(self, **_):
    #logger.debug("FocusHandler.OnGotFocus")
    pass


    if __name__ == '__main__':
    main()
    因此,要解决问题 № 1,您必须在 tkinter 主循环中输入 cef.Initialize()然后放 cef.Shutdown()之后关闭它。问题是我们仍然看不到框架,因为你没有做 grid_columnconfigure也不是 grid_rowconfigure所以即使你做了 sticky='nsew'它没有做任何事情,因为没有向行和列添加重量,为了纠正这个问题,我改用了 pack。
    在为我创建的 Windows 上:
    Image
    令人讨厌的是,这在 cefpython 上效果不佳。因为 MathJax 未加载,要纠正此问题,您需要更改 calculo.html阅读:
    <!DOCTYPE html>
    <html>
    <head>
    <title>MathJax TeX Test Page</title>
    <script type="text/x-mathjax-config" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js">
    MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
    </script>
    <script type="text/javascript" async
    src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js?config=TeX-MML-AM_CHTML">
    </script>
    </head>
    <body>
    When $a \ne 0$, there are two solutions to \(ax^2 + bx + c = 0\) and they are
    $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$ \[\\ yep \\x = {-b \pm \sqrt{b^2-4ac} \over 2a}.\]
    </body>
    </html>
    因为内联类型 text/x-mathjax-config cefpython 不支持.
    这会产生:
    CefPython with MathJax
    就像一个快速指针,在 mathjax 加载之前确实需要几秒钟,所以托管一个 local MathJax config 可能是一个想法。因为这很可能允许更快的加载时间。
    关于在这上面有一个标签,通过简单地将变量框架移动到 grid(row=1, column=0... 来编码它会相当简单。 (并更改行权重)然后在 grid(row=0, column=0... 中添加标签.

    关于python - 如何使用 CEFPython 在 Tkinter 窗口中添加 WebBrowser 小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67996093/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com