Skip to content Skip to sidebar Skip to footer

Why Can't Run Both Tkinter Mainloop And Cefpython3 Messageloop?

I'm working at a project in Python3 in which i have both tkinter and a frame in tkinter with cef browser. This is the code. from tkinter import messagebox #import threading from ce

Solution 1:

Tkinter runs in a single thread so when you write what is basically an infinite loop inside of it then you will block Tkinter from working. The only reason you screen is coming up at all is because you used update() but that will not fix the issue here.

The solution will be to use threading to manage the MessageLoop in a separate thread while also passing the frame to the function to allow for some interaction between Tkinter and cef.

Note: I also cleaned up your code a bit to better follow PEP8 standards.

import tkinter as tk
from tkinter import messagebox
from cefpython3 import cefpython as cef
import threading
import sys


def test_thread(frame):
    sys.excepthook = cef.ExceptHook
    window_info = cef.WindowInfo(frame.winfo_id())
    window_info.SetAsChild(frame.winfo_id(), rect)
    cef.Initialize()
    browser = cef.CreateBrowserSync(window_info, url='http://www.google.com')
    cef.MessageLoop()


def on_closing():
    print('closing')
    root.destroy()


root = tk.Tk()
root.geometry('800x600')
root.protocol('WM_DELETE_WINDOW', on_closing)
frame = tk.Frame(root, bg='blue', height=200)
frame2 = tk.Frame(root, bg='white', height=200)
frame.pack(side='top', fill='x')
frame2.pack(side='top', fill='x')

tk.Button(frame2, text='Exit', command=on_closing).pack(side='left')
tk.Button(frame2, text='Show something',
          command=lambda: messagebox.showinfo('TITLE', 'Shown something')).pack(side='right')

rect = [0, 0, 800, 200]
print('browser: ', rect[2], 'x', rect[3])

thread = threading.Thread(target=test_thread, args=(frame,))
thread.start()

root.mainloop()

Results:

enter image description here

Post a Comment for "Why Can't Run Both Tkinter Mainloop And Cefpython3 Messageloop?"