Python Forum
[Tkinter] can i had a cefpython3 to a labelframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] can i had a cefpython3 to a labelframe
#11
(Sep-01-2021, 01:11 PM)deanhystad Wrote: Did it run without any changes?

Yes
Reply
#12
Would you please post your attempt at using the BrowserFrame object in your tkinter program and any error information?
Reply
#13
# Example of embedding CEF Python browser using Tkinter toolkit.
# This example has two widgets: a navigation bar and a browser.
#
# NOTE: This example often crashes on Mac (Python 2.7, Tk 8.5/8.6)
#       during initial app loading with such message:
#       "Segmentation fault: 11". Reported as Issue #309.
#
# Tested configurations:
# - Tk 8.5 on Windows/Mac
# - Tk 8.6 on Linux
# - CEF Python v55.3+
#
# Known issue on Linux: When typing url, mouse must be over url
# entry widget otherwise keyboard focus is lost (Issue #255
# and Issue #284).
# Other focus issues discussed in Issue #535.


from cefpython3 import cefpython as cef
import ctypes

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import sys
import os
import platform
import logging as _logging

# Fix for PyCharm hints warnings
WindowUtils = cef.WindowUtils()

# Platforms
WINDOWS = (platform.system() == "Windows")
LINUX = (platform.system() == "Linux")
MAC = (platform.system() == "Darwin")

# Globals
logger = _logging.getLogger("tkinter_.py")

# Constants
# Tk 8.5 doesn't support png images
IMAGE_EXT = ".png" if tk.TkVersion > 8.5 else ".gif"


def main():
    logger.setLevel(_logging.DEBUG)
    stream_handler = _logging.StreamHandler()
    formatter = _logging.Formatter("[%(filename)s] %(message)s")
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)
    logger.info("CEF Python {ver}".format(ver=cef.__version__))
    logger.info("Python {ver} {arch}".format(
        ver=platform.python_version(), arch=platform.architecture()[0]))
    logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel')))
    assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this"
    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error
    # Tk must be initialized before CEF otherwise fatal error (Issue #306)
    root = tk.Tk()
    app = MainFrame(root)

    left = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                         highlightthickness=2)
    left.grid(row=0, column=0, rowspan=99, sticky='ne', pady=2)

    home_browser = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                                 highlightthickness=2)
    home_browser.grid(row=0, column=1, rowspan=99, sticky='ne', pady=2)

    right = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                                 highlightthickness=2)
    right.grid(row=0, column=2, rowspan=99, sticky='ne', pady=2)


    settings = {}
    if MAC:
        settings["external_message_pump"] = True
    cef.Initialize(settings=settings)
    app.mainloop()
    logger.debug("Main loop exited")
    cef.Shutdown()


class MainFrame(tk.Frame):

    def __init__(self, root):
        self.browser_frame = None
        self.navigation_bar = None
        self.root = root

        # Root
        root.geometry("900x640")
        tk.Grid.rowconfigure(root, 0, weight=1)
        tk.Grid.columnconfigure(root, 0, weight=1)

        # MainFrame
        tk.Frame.__init__(self, root)
        self.master.title("Tkinter example")
        self.master.protocol("WM_DELETE_WINDOW", self.on_close)
        self.master.bind("<Configure>", self.on_root_configure)
        self.setup_icon()
        self.bind("<Configure>", self.on_configure)
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)

        # NavigationBar
        self.navigation_bar = NavigationBar(self)
        self.navigation_bar.grid(row=0, column=0,
                                 sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 0, weight=0)
        tk.Grid.columnconfigure(self, 0, weight=0)

        # BrowserFrame
        self.browser_frame = BrowserFrame(self, self.navigation_bar)
        self.browser_frame.grid(row=1, column=0,
                                sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 1, weight=1)
        tk.Grid.columnconfigure(self, 0, weight=1)

        # Pack MainFrame
        self.pack(fill=tk.BOTH, expand=tk.YES)

    def on_root_configure(self, _):
        logger.debug("MainFrame.on_root_configure")
        if self.browser_frame:
            self.browser_frame.on_root_configure()

    def on_configure(self, event):
        logger.debug("MainFrame.on_configure")
        if self.browser_frame:
            width = event.width
            height = event.height
            if self.navigation_bar:
                height = height - self.navigation_bar.winfo_height()
            self.browser_frame.on_mainframe_configure(width, height)

    def on_focus_in(self, _):
        logger.debug("MainFrame.on_focus_in")

    def on_focus_out(self, _):
        logger.debug("MainFrame.on_focus_out")

    def on_close(self):
        if self.browser_frame:
            self.browser_frame.on_root_close()
            self.browser_frame = None
        else:
            self.master.destroy()

    def get_browser(self):
        if self.browser_frame:
            return self.browser_frame.browser
        return None

    def get_browser_frame(self):
        if self.browser_frame:
            return self.browser_frame
        return None

    def setup_icon(self):
        resources = os.path.join(os.path.dirname(__file__), "resources")
        icon_path = os.path.join(resources, "tkinter" + IMAGE_EXT)
        if os.path.exists(icon_path):
            self.icon = tk.PhotoImage(file=icon_path)
            # noinspection PyProtectedMember
            self.master.call("wm", "iconphoto", self.master._w, self.icon)


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()

    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="https://www.google.com/")
        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 MAC:
            # Do not use self.winfo_id() on Mac, because of these issues:
            # 1. Window id sometimes has an invalid negative value (Issue #308).
            # 2. Even with valid window id it crashes during the call to NSView.setAutoresizingMask:
            #    https://github.com/cztomczak/cefpython/issues/309#issuecomment-661094466
            #
            # To fix it using PyObjC package to obtain window handle. If you change structure of windows then you
            # need to do modifications here as well.
            #
            # There is still one issue with this solution. Sometimes there is more than one window, for example when application
            # didn't close cleanly last time Python displays an NSAlert window asking whether to Reopen that window. In such
            # case app will crash and you will see in console:
            # > Fatal Python error: PyEval_RestoreThread: NULL tstate
            # > zsh: abort      python tkinter_.py
            # Error messages related to this: https://github.com/cztomczak/cefpython/issues/441
            #
            # There is yet another issue that might be related as well:
            # https://github.com/cztomczak/cefpython/issues/583

            # noinspection PyUnresolvedReferences
            from AppKit import NSApp
            # noinspection PyUnresolvedReferences
            import objc
            logger.info("winfo_id={}".format(self.winfo_id()))
            # noinspection PyUnresolvedReferences
            content_view = objc.pyobjc_id(NSApp.windows()[-1].contentView())
            logger.info("content_view={}".format(content_view))
            return content_view
        elif 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)
            elif LINUX:
                self.browser.SetBounds(0, 0, width, height)
            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. """
        if LINUX and self.browser:
            self.browser.SetFocus(False)

    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, **_):
        logger.debug("FocusHandler.OnTakeFocus, next={next}"
                     .format(next=next_component))

    def OnSetFocus(self, source, **_):
        logger.debug("FocusHandler.OnSetFocus, source={source}"
                     .format(source=source))
        if LINUX:
            return False
        else:
            return True

    def OnGotFocus(self, **_):
        logger.debug("FocusHandler.OnGotFocus")
        if LINUX:
            self.browser_frame.focus_set()


class NavigationBar(tk.Frame):

    def __init__(self, master):
        self.back_state = tk.NONE
        self.forward_state = tk.NONE
        self.back_image = None
        self.forward_image = None
        self.reload_image = None

        tk.Frame.__init__(self, master)
        resources = os.path.join(os.path.dirname(__file__), "resources")

        # Back button
        back_png = os.path.join(resources, "back" + IMAGE_EXT)
        if os.path.exists(back_png):
            self.back_image = tk.PhotoImage(file=back_png)
        self.back_button = tk.Button(self, image=self.back_image,
                                     command=self.go_back)
        self.back_button.grid(row=0, column=0)

        # Forward button
        forward_png = os.path.join(resources, "forward" + IMAGE_EXT)
        if os.path.exists(forward_png):
            self.forward_image = tk.PhotoImage(file=forward_png)
        self.forward_button = tk.Button(self, image=self.forward_image,
                                        command=self.go_forward)
        self.forward_button.grid(row=0, column=1)

        # Reload button
        reload_png = os.path.join(resources, "reload" + IMAGE_EXT)
        if os.path.exists(reload_png):
            self.reload_image = tk.PhotoImage(file=reload_png)
        self.reload_button = tk.Button(self, image=self.reload_image,
                                       command=self.reload)
        self.reload_button.grid(row=0, column=2)

        # Url entry
        self.url_entry = tk.Entry(self)
        self.url_entry.bind("<FocusIn>", self.on_url_focus_in)
        self.url_entry.bind("<FocusOut>", self.on_url_focus_out)
        self.url_entry.bind("<Return>", self.on_load_url)
        self.url_entry.bind("<Button-1>", self.on_button1)
        self.url_entry.grid(row=0, column=3,
                            sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 0, weight=100)
        tk.Grid.columnconfigure(self, 3, weight=100)

        # Update state of buttons
        self.update_state()

    def go_back(self):
        if self.master.get_browser():
            self.master.get_browser().GoBack()

    def go_forward(self):
        if self.master.get_browser():
            self.master.get_browser().GoForward()

    def reload(self):
        if self.master.get_browser():
            self.master.get_browser().Reload()

    def set_url(self, url):
        self.url_entry.delete(0, tk.END)
        self.url_entry.insert(0, url)

    def on_url_focus_in(self, _):
        logger.debug("NavigationBar.on_url_focus_in")

    def on_url_focus_out(self, _):
        logger.debug("NavigationBar.on_url_focus_out")

    def on_load_url(self, _):
        if self.master.get_browser():
            self.master.get_browser().StopLoad()
            self.master.get_browser().LoadUrl(self.url_entry.get())

    def on_button1(self, _):
        """For focus problems see Issue #255 and Issue #535. """
        logger.debug("NavigationBar.on_button1")
        self.master.master.focus_force()

    def update_state(self):
        browser = self.master.get_browser()
        if not browser:
            if self.back_state != tk.DISABLED:
                self.back_button.config(state=tk.DISABLED)
                self.back_state = tk.DISABLED
            if self.forward_state != tk.DISABLED:
                self.forward_button.config(state=tk.DISABLED)
                self.forward_state = tk.DISABLED
            self.after(100, self.update_state)
            return
        if browser.CanGoBack():
            if self.back_state != tk.NORMAL:
                self.back_button.config(state=tk.NORMAL)
                self.back_state = tk.NORMAL
        else:
            if self.back_state != tk.DISABLED:
                self.back_button.config(state=tk.DISABLED)
                self.back_state = tk.DISABLED
        if browser.CanGoForward():
            if self.forward_state != tk.NORMAL:
                self.forward_button.config(state=tk.NORMAL)
                self.forward_state = tk.NORMAL
        else:
            if self.forward_state != tk.DISABLED:
                self.forward_button.config(state=tk.DISABLED)
                self.forward_state = tk.DISABLED
        self.after(100, self.update_state)


class Tabs(tk.Frame):

    def __init__(self):
        tk.Frame.__init__(self)
        # TODO: implement tabs


if __name__ == '__main__':
    main()
dont if this mathers but im using a Mac

Error:
[tkinter_.py] CEF Python 66.1 [tkinter_.py] Python 3.9.4 64bit [tkinter_.py] Tk 8.6.8 DevTools listening on ws://127.0.0.1:54686/devtools/browser/a6e86a9f-1bdf-46e2-aa7e-ceccb2b4b6f7 [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] winfo_id=140331657088912 [tkinter_.py] content_view=140331627491936 [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_focus_in [tkinter_.py] BrowserFrame.on_focus_in [tkinter_.py] FocusHandler.OnSetFocus, source=1 [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure [tkinter_.py] MainFrame.on_root_configure Fatal Python error: PyEval_RestoreThread: the function must be called with the GIL held, but the GIL is released (the current Python thread state is NULL) Python runtime state: initialized Current thread 0x0000000110305e00 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 1429 in mainloop File "/Users/ricardosimoes/PycharmProjects/OCP/cefpython/examples/tkinter_.py", line 80 in main File "/Users/ricardosimoes/PycharmProjects/OCP/cefpython/examples/tkinter_.py", line 444 in <module>
Reply
#14
This code really belongs in class MainFrame.__init__
    left = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                         highlightthickness=2)
    left.grid(row=0, column=0, rowspan=99, sticky='ne', pady=2)
 
    home_browser = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                                 highlightthickness=2)
    home_browser.grid(row=0, column=1, rowspan=99, sticky='ne', pady=2)
 
    right = tk.LabelFrame(app, text="", padx=5, pady=5, highlightbackground="black",
                                 highlightthickness=2)
    right.grid(row=0, column=2, rowspan=99, sticky='ne', pady=2)
left is placed in the same grid cell as navigation_bar
    left.grid(row=0, column=0, rowspan=99, sticky='ne', pady=2)
       self.navigation_bar.grid(row=0, column=0,
                                 sticky=(tk.N + tk.S + tk.E + tk.W))
I don't know, but think this may be your main problem because it removes the Navigation bar, and thus the browser, from the MainFrame. As mentioned in the comments in get_window_handle, the MAC version is kind of brittle and it is easy to make it crash.
Quote: # There is still one issue with this solution. Sometimes there is more than one window, for example when application
# didn't close cleanly last time Python displays an NSAlert window asking whether to Reopen that window. In such
# case app will crash and you will see in console:
# > Fatal Python error: PyEval_RestoreThread: NULL tstate1
That is the error message you are getting when your program crashes.

Why are you setting rowspan=99? Is that a sloppy way to say "I am the only thing in this column?" Sloppy meaning imprecise, not bad. Maybe bad.
Reply
#15
i dont get any error but the browser window doesnt show untill i resize the window

# Example of embedding CEF Python browser using Tkinter toolkit.
# This example has two widgets: a navigation bar and a browser.
#
# NOTE: This example often crashes on Mac (Python 2.7, Tk 8.5/8.6)
#       during initial app loading with such message:
#       "Segmentation fault: 11". Reported as Issue #309.
#
# Tested configurations:
# - Tk 8.5 on Windows/Mac
# - Tk 8.6 on Linux
# - CEF Python v55.3+
#
# Known issue on Linux: When typing url, mouse must be over url
# entry widget otherwise keyboard focus is lost (Issue #255
# and Issue #284).
# Other focus issues discussed in Issue #535.


from cefpython3 import cefpython as cef
import ctypes

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk
import sys
import os
import platform
import logging as _logging

# Fix for PyCharm hints warnings
WindowUtils = cef.WindowUtils()

# Platforms
WINDOWS = (platform.system() == "Windows")
LINUX = (platform.system() == "Linux")
MAC = (platform.system() == "Darwin")

# Globals
logger = _logging.getLogger("tkinter_.py")

# Constants
# Tk 8.5 doesn't support png images
IMAGE_EXT = ".png" if tk.TkVersion > 8.5 else ".gif"


def main():
    logger.setLevel(_logging.DEBUG)
    stream_handler = _logging.StreamHandler()
    formatter = _logging.Formatter("[%(filename)s] %(message)s")
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)
    logger.info("CEF Python {ver}".format(ver=cef.__version__))
    logger.info("Python {ver} {arch}".format(
        ver=platform.python_version(), arch=platform.architecture()[0]))
    logger.info("Tk {ver}".format(ver=tk.Tcl().eval('info patchlevel')))
    assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this"
    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error
    # Tk must be initialized before CEF otherwise fatal error (Issue #306)
    root = tk.Tk()
    app = MainFrame(root)




    settings = {}
    if MAC:
        settings["external_message_pump"] = True
    cef.Initialize(settings=settings)
    app.mainloop()
    logger.debug("Main loop exited")
    cef.Shutdown()


class MainFrame(tk.Frame):

    def __init__(self, root):
        self.browser_frame = None
        self.navigation_bar = None
        self.root = root

        # Root
        root.geometry("900x640")
        tk.Grid.rowconfigure(root, 0, weight=1)
        tk.Grid.columnconfigure(root, 0, weight=1)

        # MainFrame
        tk.Frame.__init__(self, root)
        self.master.title("Tkinter example")
        self.master.protocol("WM_DELETE_WINDOW", self.on_close)
        self.master.bind("<Configure>", self.on_root_configure)
        self.setup_icon()
        self.bind("<Configure>", self.on_configure)
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)

        # NavigationBar
        left = tk.LabelFrame(root, text="lefttttttttttttt", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
        left.grid(row=0, column=0, rowspan=99, sticky='ne', pady=2)

        home_browser = tk.LabelFrame(root, text="browserrrrrrrrr", padx=5, pady=5, highlightbackground="black",
                                     highlightthickness=2)
        home_browser.grid(row=0, column=1, rowspan=99, sticky='ne', pady=2)

        right = tk.LabelFrame(root, text="rightttttttttt", padx=5, pady=5, highlightbackground="black",
                              highlightthickness=2)
        right.grid(row=0, column=2, rowspan=99, sticky='ne', pady=2)


        self.navigation_bar = NavigationBar(self)
        self.navigation_bar.grid(row=0, column=0,
                                 sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 0, weight=0)
        tk.Grid.columnconfigure(self, 0, weight=0)

        # BrowserFrame
        self.browser_frame = BrowserFrame(self, self.navigation_bar)
        self.browser_frame.grid(row=1, column=0,
                                sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 1, weight=1)
        tk.Grid.columnconfigure(self, 0, weight=1)

        # Pack MainFrame
        self.grid(row=0, column=0)

    def on_root_configure(self, _):
        logger.debug("MainFrame.on_root_configure")
        if self.browser_frame:
            self.browser_frame.on_root_configure()

    def on_configure(self, event):
        logger.debug("MainFrame.on_configure")
        if self.browser_frame:
            width = event.width
            height = event.height
            if self.navigation_bar:
                height = height - self.navigation_bar.winfo_height()
            self.browser_frame.on_mainframe_configure(width, height)

    def on_focus_in(self, _):
        logger.debug("MainFrame.on_focus_in")

    def on_focus_out(self, _):
        logger.debug("MainFrame.on_focus_out")

    def on_close(self):
        if self.browser_frame:
            self.browser_frame.on_root_close()
            self.browser_frame = None
        else:
            self.master.destroy()

    def get_browser(self):
        if self.browser_frame:
            return self.browser_frame.browser
        return None

    def get_browser_frame(self):
        if self.browser_frame:
            return self.browser_frame
        return None

    def setup_icon(self):
        resources = os.path.join(os.path.dirname(__file__), "resources")
        icon_path = os.path.join(resources, "tkinter" + IMAGE_EXT)
        if os.path.exists(icon_path):
            self.icon = tk.PhotoImage(file=icon_path)
            # noinspection PyProtectedMember
            self.master.call("wm", "iconphoto", self.master._w, self.icon)


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()

    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="https://www.google.com/")
        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 MAC:
            # Do not use self.winfo_id() on Mac, because of these issues:
            # 1. Window id sometimes has an invalid negative value (Issue #308).
            # 2. Even with valid window id it crashes during the call to NSView.setAutoresizingMask:
            #    https://github.com/cztomczak/cefpython/issues/309#issuecomment-661094466
            #
            # To fix it using PyObjC package to obtain window handle. If you change structure of windows then you
            # need to do modifications here as well.
            #
            # There is still one issue with this solution. Sometimes there is more than one window, for example when application
            # didn't close cleanly last time Python displays an NSAlert window asking whether to Reopen that window. In such
            # case app will crash and you will see in console:
            # > Fatal Python error: PyEval_RestoreThread: NULL tstate
            # > zsh: abort      python tkinter_.py
            # Error messages related to this: https://github.com/cztomczak/cefpython/issues/441
            #
            # There is yet another issue that might be related as well:
            # https://github.com/cztomczak/cefpython/issues/583

            # noinspection PyUnresolvedReferences
            from AppKit import NSApp
            # noinspection PyUnresolvedReferences
            import objc
            logger.info("winfo_id={}".format(self.winfo_id()))
            # noinspection PyUnresolvedReferences
            content_view = objc.pyobjc_id(NSApp.windows()[-1].contentView())
            logger.info("content_view={}".format(content_view))
            return content_view
        elif 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)
            elif LINUX:
                self.browser.SetBounds(0, 0, width, height)
            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. """
        if LINUX and self.browser:
            self.browser.SetFocus(False)

    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, **_):
        logger.debug("FocusHandler.OnTakeFocus, next={next}"
                     .format(next=next_component))

    def OnSetFocus(self, source, **_):
        logger.debug("FocusHandler.OnSetFocus, source={source}"
                     .format(source=source))
        if LINUX:
            return False
        else:
            return True

    def OnGotFocus(self, **_):
        logger.debug("FocusHandler.OnGotFocus")
        if LINUX:
            self.browser_frame.focus_set()


class NavigationBar(tk.Frame):

    def __init__(self, master):
        self.back_state = tk.NONE
        self.forward_state = tk.NONE
        self.back_image = None
        self.forward_image = None
        self.reload_image = None

        tk.Frame.__init__(self, master)
        resources = os.path.join(os.path.dirname(__file__), "resources")

        # Back button
        back_png = os.path.join(resources, "back" + IMAGE_EXT)
        if os.path.exists(back_png):
            self.back_image = tk.PhotoImage(file=back_png)
        self.back_button = tk.Button(self, image=self.back_image,
                                     command=self.go_back)
        self.back_button.grid(row=0, column=0)

        # Forward button
        forward_png = os.path.join(resources, "forward" + IMAGE_EXT)
        if os.path.exists(forward_png):
            self.forward_image = tk.PhotoImage(file=forward_png)
        self.forward_button = tk.Button(self, image=self.forward_image,
                                        command=self.go_forward)
        self.forward_button.grid(row=0, column=1)

        # Reload button
        reload_png = os.path.join(resources, "reload" + IMAGE_EXT)
        if os.path.exists(reload_png):
            self.reload_image = tk.PhotoImage(file=reload_png)
        self.reload_button = tk.Button(self, image=self.reload_image,
                                       command=self.reload)
        self.reload_button.grid(row=0, column=2)

        # Url entry
        self.url_entry = tk.Entry(self)
        self.url_entry.bind("<FocusIn>", self.on_url_focus_in)
        self.url_entry.bind("<FocusOut>", self.on_url_focus_out)
        self.url_entry.bind("<Return>", self.on_load_url)
        self.url_entry.bind("<Button-1>", self.on_button1)
        self.url_entry.grid(row=0, column=3,
                            sticky=(tk.N + tk.S + tk.E + tk.W))
        tk.Grid.rowconfigure(self, 0, weight=100)
        tk.Grid.columnconfigure(self, 3, weight=100)

        # Update state of buttons
        self.update_state()

    def go_back(self):
        if self.master.get_browser():
            self.master.get_browser().GoBack()

    def go_forward(self):
        if self.master.get_browser():
            self.master.get_browser().GoForward()

    def reload(self):
        if self.master.get_browser():
            self.master.get_browser().Reload()

    def set_url(self, url):
        self.url_entry.delete(0, tk.END)
        self.url_entry.insert(0, url)

    def on_url_focus_in(self, _):
        logger.debug("NavigationBar.on_url_focus_in")

    def on_url_focus_out(self, _):
        logger.debug("NavigationBar.on_url_focus_out")

    def on_load_url(self, _):
        if self.master.get_browser():
            self.master.get_browser().StopLoad()
            self.master.get_browser().LoadUrl(self.url_entry.get())

    def on_button1(self, _):
        """For focus problems see Issue #255 and Issue #535. """
        logger.debug("NavigationBar.on_button1")
        self.master.master.focus_force()

    def update_state(self):
        browser = self.master.get_browser()
        if not browser:
            if self.back_state != tk.DISABLED:
                self.back_button.config(state=tk.DISABLED)
                self.back_state = tk.DISABLED
            if self.forward_state != tk.DISABLED:
                self.forward_button.config(state=tk.DISABLED)
                self.forward_state = tk.DISABLED
            self.after(100, self.update_state)
            return
        if browser.CanGoBack():
            if self.back_state != tk.NORMAL:
                self.back_button.config(state=tk.NORMAL)
                self.back_state = tk.NORMAL
        else:
            if self.back_state != tk.DISABLED:
                self.back_button.config(state=tk.DISABLED)
                self.back_state = tk.DISABLED
        if browser.CanGoForward():
            if self.forward_state != tk.NORMAL:
                self.forward_button.config(state=tk.NORMAL)
                self.forward_state = tk.NORMAL
        else:
            if self.forward_state != tk.DISABLED:
                self.forward_button.config(state=tk.DISABLED)
                self.forward_state = tk.DISABLED
        self.after(100, self.update_state)


class Tabs(tk.Frame):

    def __init__(self):
        tk.Frame.__init__(self)
        # TODO: implement tabs


if __name__ == '__main__':
    main()
Reply
#16
Even thou how do i implement it in my project?


for example this is one of two places were i need a browser window

from tkinter import *
from tkinter import ttk
import tkinter as tk
from formularios import tabmain0
import requests
from bs4 import BeautifulSoup
import webbrowser
import tkinterweb

def home():
    container = ttk.Frame(tabmain0)
    canvas = tk.Canvas(container)
    scrollbar_x = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
    scrollbar_y = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
    scrollable_frame = ttk.Frame(canvas)

    scrollable_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

    canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

    canvas.configure(xscrollcommand=scrollbar_x.set)
    canvas.configure(yscrollcommand=scrollbar_y.set)
    
    stathomelib = LabelFrame(scrollable_frame, text="Library", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomelib.grid(row=3, column=0, columnspan=2, sticky=NW, pady=2)

    stathomedoc = LabelFrame(scrollable_frame, text="Documentation", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomedoc.grid(row=3, column=2, columnspan=2,sticky=NW, pady=2)

    stathomeTools = LabelFrame(scrollable_frame, text="External Tools", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomeTools.grid(row=3, column=4, columnspan=2, sticky=NW, pady=2)

    stathomekib = LabelFrame(scrollable_frame, text="Kibana", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomekib.grid(row=0, column=0, sticky=NW, pady=2)

    stathomeSDC = LabelFrame(scrollable_frame, text="SDC", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomeSDC.grid(row=0, column=1, sticky=NW, pady=2)

    stathomeshiny = LabelFrame(scrollable_frame, text="Shiny", padx=5, pady=5, highlightbackground="black",
                               highlightthickness=2)
    stathomeshiny.grid(row=0, column=2, sticky=NW, pady=2)

    stathomeSMART = LabelFrame(scrollable_frame, text="SMART", padx=5, pady=5, highlightbackground="black",
                               highlightthickness=2)
    stathomeSMART.grid(row=0, column=3, sticky=NW, pady=2)

    stathomeVPN = LabelFrame(scrollable_frame, text="Open VPN", padx=5, pady=5, highlightbackground="black",
                               highlightthickness=2)
    stathomeVPN.grid(row=0, column=4, sticky=NW, pady=2)

    home_browser = LabelFrame(scrollable_frame, text="", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    home_browser.grid(row=0, column=99, rowspan=99, sticky='ne', pady=2)
    valido_browser = tk.IntVar()
    valido_browser.set(False)

    checkbrowser = tk.Checkbutton(home_browser, fg="blue", selectcolor="red", text="Open in Browser", variable=valido_browser)
    checkbrowser.grid(row=0, column=0, columnspan=9, sticky="wn")



    def choose_browser(urlbook):
        if valido_browser.get() == 1:
            webbrowser.open(urlbook)
        else:
            #frm_browser_home.insert(tk.INSERT, urlbook)
            frame = tkinterweb.HtmlFrame(home_browser,messages_enabled = False)
            urlbook=urlbook
            frame.load_website(urlbook)
            frame.grid(row=1, column=0,sticky="wnse", ipadx=330, ipady=120)

    choose_browser("http://www.google.com")


    global varLnkOrder
    varLnkOrder = ""
    varLbook = open("Confs/bookmarks.txt", "r").readlines()
    try:
        for line in varLbook:
            undef = ""
            if ":stathomelib" in line:
                varLnkOrder = stathomelib
                taman=43
                c = 0
                i = 0

            elif ":stathomedoc" in line:
                varLnkOrder = stathomedoc
                taman=43
                c = 0
                i = 0

            elif ":stathomekib" in line:
                varLnkOrder = stathomekib
                taman = 20
                c = 0
                i = 0

            elif ":stathomeSDC" in line:
                varLnkOrder = stathomeSDC
                taman = 20
                c = 0
                i = 0

            elif ":stathomeshiny" in line:
                varLnkOrder = stathomeshiny
                taman = 20
                c = 0
                i = 0

            elif ":stathomeSMART" in line:
                varLnkOrder = stathomeSMART
                taman = 20
                c = 0
                i = 0

            elif ":stathomeVPN" in line:
                try:
                    url = "https://httpd-openvpn.dev/active.php"
                    r = requests.get(url, allow_redirects=False)
                    if r.status_code == 200:
                        soup = BeautifulSoup(r.content, 'lxml')
                        words = soup.find(text=lambda text: text and "UNDEF" in text)
                        if ((words) == "UNDEF"):
                            undef = " (UNDEF Found)"
                    else:
                        undef = " (Down!!!)"
                except Exception as e:
                    undef = " (Down!!!)"

                varLnkOrder = stathomeVPN
                taman = 20
                c = 0
                i = 0

            elif ":stathomeTools" in line:
                varLnkOrder = stathomeTools
                taman = 20
                c = 0
                i = 0



            if len(line) > 1:

                titul, urlbook = line.split('<=>')
                if len(titul) > 1:
                    link1 = Label(varLnkOrder, width=taman, text=titul+str(undef), justify="left", anchor="center", fg="blue", cursor="draft_large")
                    link1.grid(row=i, column=c, sticky="n", pady=2)
                    link1.bind("<Button-1>", lambda e, urlbook=urlbook: choose_browser(urlbook.rstrip()))
                    i += 1
                    line == ""

    except Exception as e:
        from main import log_error
        log_error(e, "Bookmark_Builder")

    container.pack(expand=1, fill="both")
    scrollbar_x.pack(side="bottom", fill="x")
    scrollbar_y.pack(side="right", fill="y")
    canvas.pack(side="bottom", fill="both", expand=True)
here you can see a working example with tkinterweb, unfortunally this browser module dont read most of the websites.


i would be perfect if i could have a function to call, something like, open_browser(frame_name, url)
Reply
#17
import ctypes
import platform
import sys
import tkinter as tk
from cefpython3 import cefpython as cef
from tkinter import *
from tkinter import ttk
import tkinter as tk

import requests
from bs4 import BeautifulSoup
import webbrowser
import tkinterweb


# platforms
WINDOWS = platform.system() == 'Windows'
LINUX = platform.system() == 'Linux'
MAC = platform.system() == 'Darwin'

class BrowserFrame(tk.Frame):
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self.browser = None
        self.bind('<Configure>', self.on_configure)

    def get_window_handle(self):
        if MAC:
            from AppKit import NSApp
            import objc
            return objc.pyobjc_id(NSApp.windows()[-1].contentView())
        elif self.winfo_id() > 0:
            return self.winfo_id()
        else:
            raise Exception('Could not obtain window handle!')

    def on_configure(self, event):
        if self.browser is None:
            # create the browser and embed it in current frame
            rect = [0, 0, self.winfo_width(), self.winfo_height()]
            cef_winfo = cef.WindowInfo()
            win_id = self.get_window_handle()
            cef_winfo.SetAsChild(win_id, rect)
            self.browser = cef.CreateBrowserSync(cef_winfo, url="https://www.google.com/")

            # start the browser handling loop
            self.cef_loop()

        # resize the browser
        if WINDOWS:
            ctypes.windll.user32.SetWindowPos(
                self.browser.GetWindowHandle(), 0,
                0, 0, event.width, event.height, 0x0002)
        elif LINUX:
            self.browser.SetBounds(0, 0, event.width, event.height)

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


def main():
    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error

    root = tk.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w, h))
    root.title('Test')

    settings = {}
    if MAC:
        settings["external_message_pump"] = True

    cef.Initialize(settings=settings)

    container = ttk.Frame(root)
    canvas = tk.Canvas(container)
    scrollbar_x = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
    scrollbar_y = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
    scrollable_frame = ttk.Frame(canvas)

    scrollable_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

    canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

    canvas.configure(xscrollcommand=scrollbar_x.set)
    canvas.configure(yscrollcommand=scrollbar_y.set)

    stathomelib = LabelFrame(scrollable_frame, text="Library", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomelib.grid(row=3, column=0, columnspan=2, sticky=NW, pady=2)

    stathomedoc = LabelFrame(scrollable_frame, text="Documentation", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomedoc.grid(row=3, column=2, columnspan=2, sticky=NW, pady=2)

    stathomeTools = LabelFrame(scrollable_frame, text="External Tools", padx=5, pady=5, highlightbackground="black",
                               highlightthickness=2)
    stathomeTools.grid(row=3, column=4, columnspan=2, sticky=NW, pady=2)



    home_browser = LabelFrame(scrollable_frame, text="", padx=5, pady=5, highlightbackground="black",highlightthickness=2)
    home_browser.grid(row=0, column=99, rowspan=99, sticky='ne', pady=2)

    valido_browser = tk.IntVar()
    valido_browser.set(False)
    checkbrowser = tk.Checkbutton(home_browser, fg="blue", selectcolor="red", text="Open in Browser",variable=valido_browser)
    checkbrowser.grid(row=0, column=0, columnspan=9, sticky="wn")

    BrowserFrame(home_browser).grid(row=2, column=0, columnspan=9, sticky="wn")

    def choose_browser(urlbook):
        if valido_browser.get() == 1:
            webbrowser.open(urlbook)
        else:
            # frm_browser_home.insert(tk.INSERT, urlbook)
            frame = tkinterweb.HtmlFrame(home_browser, messages_enabled=False)
            urlbook = urlbook
            frame.load_website(urlbook)
            frame.grid(row=1, column=0, sticky="wnse", ipadx=330, ipady=120)

    choose_browser("http://www.google.com")

    global varLnkOrder
    varLnkOrder = ""
    varLbook = open("bookmarks.txt", "r").readlines()
    try:
        for line in varLbook:
            undef = ""
            if ":stathomelib" in line:
                varLnkOrder = stathomelib
                taman = 43
                c = 0
                i = 0

            elif ":stathomedoc" in line:
                varLnkOrder = stathomedoc
                taman = 43
                c = 0
                i = 0

            elif ":stathomeTools" in line:
                varLnkOrder = stathomeTools
                taman = 20
                c = 0
                i = 0

            if len(line) > 1:

                titul, urlbook = line.split('<=>')
                if len(titul) > 1:
                    link1 = Label(varLnkOrder, width=taman, text=titul + str(undef), justify="left", anchor="center",
                                  fg="blue", cursor="draft_large")
                    link1.grid(row=i, column=c, sticky="n", pady=2)
                    link1.bind("<Button-1>", lambda e, urlbook=urlbook: choose_browser(urlbook.rstrip()))
                    i += 1
                    line == ""

    except Exception as e:
        from main import log_error
        log_error(e, "Bookmark_Builder")

    container.pack(expand=1, fill="both")
    scrollbar_x.pack(side="bottom", fill="x")
    scrollbar_y.pack(side="right", fill="y")
    canvas.pack(side="bottom", fill="both", expand=True)

    root.mainloop()
    cef.Shutdown()

if __name__ == '__main__':
    main()
bookmarks.txt
Quote:<=>:stathomelib
aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/ aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrth

<=>:stathomedoc
Wiki Teltonika Commands<=>https://wiki.teltonika-gps.com/view/FMB_SMS/GPRS_Commands Lucene Query Syntax(LogTrail Search)<=>http://www.lucenetutorial.com/lucene-query-syntax.html aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/ aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/ aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/

<=>:stathomeTools
aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/ aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug
Reply
#18
(Sep-02-2021, 07:48 AM)razs Wrote: Even thou how do i implement it in my project?
I think you would create an instance of NavigationBar inside home_browser. Put the example somewhere in your python path so you can import NavigationBar. I recommend the same directory as the other python files for the project. Create your tkinter app and make a frame that will contain the browser (home_browser from your example), then just make a NavigationBar that will be the only object in the frame. If you don't want the navigation bar create an instance of BrowserFrame instead.

If the browser does not appear in browser_frame it is probably because the browser_frame is not resizing or because browser_frame is not resizing it's contents.
Reply
#19
This is what i got so far, but it opens full window on mac.... in windows it opens fine, do you know how to get it to work on mac properly?

import ctypes
import platform
import sys
import tkinter as tk
from cefpython3 import cefpython as cef
from tkinter import *
from tkinter import ttk
import tkinter as tk

import requests
from bs4 import BeautifulSoup
import webbrowser
import tkinterweb


# platforms
WINDOWS = platform.system() == 'Windows'
LINUX = platform.system() == 'Linux'
MAC = platform.system() == 'Darwin'

class BrowserFrame(tk.Frame):
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self.browser = None
        self.bind('<Configure>', self.on_configure)

    def get_window_handle(self):
        if MAC:
            from AppKit import NSApp
            import objc
            return objc.pyobjc_id(NSApp.windows()[-1].contentView())
        elif self.winfo_id() > 0:
            return self.winfo_id()
        else:
            raise Exception('Could not obtain window handle!')

    def on_configure(self, event):
        if self.browser is None:
            # create the browser and embed it in current frame
            rect = [0, 0, self.winfo_width(), self.winfo_height()]
            cef_winfo = cef.WindowInfo()
            win_id = self.get_window_handle()
            cef_winfo.SetAsChild(win_id, rect)
            self.browser = cef.CreateBrowserSync(cef_winfo, url=urlset)

            # start the browser handling loop
            self.cef_loop()

        # resize the browser
        if WINDOWS:
            ctypes.windll.user32.SetWindowPos(
                self.browser.GetWindowHandle(), 0,
                0, 0, event.width, event.height, 0x0002)
        elif LINUX:
            self.browser.SetBounds(0, 0, event.width, event.height)

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


def main():

    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error

    root = tk.Tk()
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w, h))
    root.title('Test')

    settings = {}
    if MAC:
        settings["external_message_pump"] = True

    cef.Initialize(settings=settings)

    container = ttk.Frame(root)
    canvas = tk.Canvas(container)
    scrollbar_x = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
    scrollbar_y = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
    scrollable_frame = ttk.Frame(canvas)

    scrollable_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

    canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

    canvas.configure(xscrollcommand=scrollbar_x.set)
    canvas.configure(yscrollcommand=scrollbar_y.set)

    stathomelib = LabelFrame(scrollable_frame, text="Library", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomelib.grid(row=3, column=0, columnspan=2, sticky=NW, pady=2)

    stathomedoc = LabelFrame(scrollable_frame, text="Documentation", padx=5, pady=5, highlightbackground="black",
                             highlightthickness=2)
    stathomedoc.grid(row=3, column=2, columnspan=2, sticky=NW, pady=2)

    home_browser = LabelFrame(scrollable_frame, text="", padx=5, pady=5, highlightbackground="black",highlightthickness=2)
    home_browser.grid(row=0, column=99, rowspan=99, sticky='ne', pady=2)

    valido_browser = tk.IntVar()
    valido_browser.set(False)
    checkbrowser = tk.Checkbutton(home_browser, fg="blue", selectcolor="red", text="Open in Browser",variable=valido_browser)
    checkbrowser.grid(row=0, column=0, columnspan=9, sticky="wn")

    BrowserFrame(home_browser).grid(row=2, column=0, columnspan=9, sticky="wn")



    def choose_browser(urlbook):
        if valido_browser.get() == 1:
            webbrowser.open(urlbook)
        else:
            global urlset
            urlset = urlbook

    choose_browser("http://www.google.com")


    global varLnkOrder
    varLnkOrder = ""
    varLbook = open("Confs/bookmarks.txt", "r").readlines()
    try:
        for line in varLbook:
            undef = ""
            if ":stathomelib" in line:
                varLnkOrder = stathomelib
                taman = 43
                c = 0
                i = 0

            elif ":stathomedoc" in line:
                varLnkOrder = stathomedoc
                taman = 43
                c = 0
                i = 0



            if len(line) > 1:

                titul, urlbook = line.split('<=>')
                if len(titul) > 1:
                    link1 = Label(varLnkOrder, width=taman, text=titul + str(undef), justify="left", anchor="center",
                                  fg="blue", cursor="draft_large")
                    link1.grid(row=i, column=c, sticky="n", pady=2)
                    link1.bind("<Button-1>", lambda e, urlbook=urlbook: choose_browser(urlbook.rstrip()))
                    i += 1
                    line == ""

    except Exception as e:
        from main import log_error
        log_error(e, "Bookmark_Builder")

    container.pack(expand=1, fill="both")
    scrollbar_x.pack(side="bottom", fill="x")
    scrollbar_y.pack(side="right", fill="y")
    canvas.pack(side="bottom", fill="both", expand=True)

    root.mainloop()

if __name__ == '__main__':
    main()
Reply
#20
still strugling with this :s

i got this and it works with the exception that the frame opens in the bottom of the page after i resize it

import ctypes
import platform
from cefpython3 import cefpython as cef
from tkinter import *
import tkinter as tk
import sys
# platforms
from cefpython.examples.tkinter_ import logger

WINDOWS = platform.system() == 'Windows'
LINUX = platform.system() == 'Linux'
MAC = platform.system() == 'Darwin'


class BrowserFrame(tk.Frame):
    def __init__(self, master=None, **kw):
        super().__init__(master, **kw)
        self.browser = None
        self.bind('<Configure>', self.on_configure)


    def get_window_handle(self):
        if MAC:
            from AppKit import NSApp
            import objc
            return objc.pyobjc_id(NSApp.windows()[-1].contentView())
        elif self.winfo_id() > 0:
            return self.winfo_id()
        else:
            raise Exception('Could not obtain window handle!')

    def on_configure(self, event):
        if self.browser is None:
            # create the browser and embed it in current frame

            self.update()
            rect = [0, 0, self.winfo_width(), self.winfo_height()]
            cef_winfo = cef.WindowInfo()
            win_id = self.get_window_handle()
            cef_winfo.SetAsChild(win_id, rect)


            self.browser = cef.CreateBrowserSync(cef_winfo, url=urlset)

            # start the browser handling loop
            self.cef_loop()

        # resize the browser
        if WINDOWS:
            ctypes.windll.user32.SetWindowPos(
                self.browser.GetWindowHandle(), 0,
                0, 0, event.width, event.height, 0x0002)
        elif LINUX:
            self.browser.SetBounds(0, 0, event.width, event.height)

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


def main():

    root = tk.Tk()
    root.minsize(600, 600)
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w-550, h-250))
    root.title('Test')

    WindowUtils = cef.WindowUtils()
    sys.excepthook = cef.ExceptHook  # To shutdown all CEF processes on error
    settings = {}
    if MAC:
        settings["external_message_pump"] = True

    cef.Initialize(settings=settings)

    leftfrm = LabelFrame(root, text="left frame for buttons with links", padx=5, pady=5, highlightbackground="black", highlightthickness=2)
    leftfrm.grid(row=0, column=0, rowspan=99, sticky='nw', pady=2)

    home_browser = LabelFrame(root, text="right frame for browser", padx=5, pady=5, highlightbackground="black", highlightthickness=2)
    home_browser.grid(row=0, column=1, rowspan=99, sticky='ne', pady=2)

    browser_frame = BrowserFrame(home_browser).grid(row=1, column=0, sticky=(tk.N + tk.S + tk.E + tk.W))

    for x in range(1, 25):
        Label(leftfrm, text=str("Link "+str(x))).grid(row=x,column=0)

    global urlset
    urlset = "http://www.google.com"

    root.mainloop()

if __name__ == '__main__':
    main()
[Image: 6e99ec442a2fea1bedb081e65e6e1534.png]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter destroy label inside labelFrame Nick_tkinter 3 4,565 Sep-17-2023, 03:38 PM
Last Post: munirashraf9821
  Issue in Tkinter with winfo_class() and LabelFrame ReDefendeur 1 2,757 Oct-05-2020, 05:52 AM
Last Post: Jeff900

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020