本文介绍了使用 cef 在 tkinter 上设置框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮忙吗?

我用框架定义了我的页面,但是当我运行代码时,它只显示浏览器窗口.

I have my page defined with frames but when i run the code it only shows the browser window.

这个问题是在labelframe中加载CEF

它基本上是一个带有链接的窗口,右侧是一个浏览器窗口

Its basicly a window with links and a browser window on the right

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

import requests
from bs4 import BeautifulSoup
import webbrowser
import tkinterweb

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

# 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 open(self, url):
        if self.browser:
            self.browser.LoadUrl(url)

    # inside BrowserFrame
    def on_configure(self, event):
        if self.browser is None:
            self.browser = cef.CreateBrowserSync(cef_winfo,url=urlset)


    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 = tk.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 = tk.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 = tk.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")


    # specify initial width and height
    browser = BrowserFrame(home_browser, width=1200, height=700)
    browser.grid(row=2, column=0, columnspan=9, sticky="wn")

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



    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 = tk.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()

书签.txt

:stathomelibaaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyugaaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrth

:stathomedoc Wiki Teltonika命令https://wiki.teltonika-gps.com/view/FMB_SMS/GPRS_CommandsLucene 查询语法(LogTrail搜索)http://www.lucenetutorial.com/lucene-query-syntax.htmlaaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/

<=>:stathomedoc Wiki TeltonikaCommands<=>https://wiki.teltonika-gps.com/view/FMB_SMS/GPRS_CommandsLucene Query Syntax(LogTrailSearch)<=>http://www.lucenetutorial.com/lucene-query-syntax.htmlaaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/

:stathome工具aaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdeeryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/

<=>:stathomeToolsaaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/aaaaswefdee<=>ryweryfgertgjhslkrghkjreshjglkjhlksghklrhsklrhklegrthuyug/

推荐答案

请注意,更新 urlset 不会自动在 CEF 浏览器中加载 URL.您需要在 BrowserFrame 中创建一个函数来加载 URL:

Note that updating urlset will not load the URL in the CEF browser automatically. You need to create a function in BrowserFrame to load an URL:

# inside BrowserFrame
def open(self, url):
    if self.browser:
        self.browser.LoadUrl(url)

并且在创建 CEF 浏览器时需要加载一个默认 URL:

And you need to load a default URL when creating the CEF browser:

# inside BrowserFrame
def on_configure(self, event):
    if self.browser is None:
        ...
        self.browser = cef.CreateBrowserSync(cef_winfo,
                                             url="https://www.google.com")
    ...

然后更新main()如下:

def main():
    ...
    # specify initial width and height
    browser = BrowserFrame(home_browser, width=1200, height=700)
    browser.grid(row=2, column=0, columnspan=9, sticky="wn")

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

    # not necessary to call choose_browser() here
    #choose_browser("http://www.google.com")
    ...


不建议像下面这样导入相同的模块:


It is not recommended to import same module like below:

from tkinter import *
import tkinter as tk

最好只使用后者.

这篇关于使用 cef 在 tkinter 上设置框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 17:08