我编辑了CEFpython的github页面中的代码,该页面使用wxPython。它在我的mac电脑上运行良好,但当浏览器在windows上启动时,它只会加载一个空白的白色屏幕。在
我第一次尝试wxPython和CEFpython。 我尝试使用wxPython作为cef浏览器的包装器,在后台使用django作为服务器。 我遵循了CEFpython的Github页面https://github.com/cztomczak/cefpython/blob/master/examples/wxpython.py的教程 我编辑了它,它在mac上运行,但当我试图在windows上运行它时,我得到的是一个空白的白色页面,上面有一个小的正方形。 我所做的: 1) 我试着装谷歌而不是127.0.0.1:8000。 2) 我猜可能是服务器在包含浏览器的帧之前没有启动,我用一个线程延迟了大约15秒,并在浏览器上调用了Reload 3) 它在Mac上运行得很好,所以我编辑了代码,只留下了与windows相关的代码,同样的事情。 请帮忙! 抱歉,如果我粘贴了所有的代码,我真的不知道我做错了什么。 提前谢谢你。在
在浏览器.py在
import wx
from cefpython3 import cefpython as cef
import sys
import platform
import os
# Platforms
WINDOWS = (platform.system() == "Windows")
LINUX = (platform.system() == "Linux")
MAC = (platform.system() == "Darwin")
if MAC:
try:
# noinspection PyUnresolvedReferences
from AppKit import NSApp
except ImportError:
print("[wxpython.py] Error: PyObjC package is missing, "
"cannot fix Issue #371")
print("[wxpython.py] To install PyObjC type: "
"pip install -U pyobjc")
sys.exit(1)
def check_versions():
print("[wxpython.py] CEF Python {ver}".format(ver=cef.__version__))
print("[wxpython.py] Python {ver} {arch}".format(
ver=platform.python_version(), arch=platform.architecture()[0]))
print("[wxpython.py] wxPython {ver}".format(ver=wx.version()))
# CEF Python version requirement
assert cef.__version__ >= "66.0", "CEF Python v66.0+ required to run this"
def scale_window_size_for_high_dpi(width, height):
"""Scale window size for high DPI devices. This func can be
called on all operating systems, but scales only for Windows.
If scaled value is bigger than the work area on the display
then it will be reduced."""
if not WINDOWS:
return width, height
(_, _, max_width, max_height) = wx.GetClientDisplayRect().Get()
# noinspection PyUnresolvedReferences
(width, height) = cef.DpiAware.Scale((width, height))
if width > max_width:
width = max_width
if height > max_height:
height = max_height
return width, height
class BrowserFrame(wx.Frame):
def __init__(self):
self.browser = None
wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title="NETS Framework")
self.ShowFullScreen(True)
# Set wx.WANTS_CHARS style for the keyboard to work.
# This style also needs to be set for all parent controls.
self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS)
self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize)
check_versions()
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
settings = {}
settings["context_menu"] = {'enabled':False}
if MAC:
# Issue #442 requires enabling message pump on Mac
# and calling message loop work in a timer both at
# the same time. This is an incorrect approach
# and only a temporary fix.
settings["external_message_pump"] = True
if WINDOWS:
# noinspection PyUnresolvedReferences, PyArgumentList
cef.DpiAware.EnableHighDpiSupport()
cef.Initialize(settings=settings)
if MAC:
# Make the content view for the window have a layer.
# This will make all sub-views have layers. This is
# necessary to ensure correct layer ordering of all
# child views and their layers. This fixes Window
# glitchiness during initial loading on Mac (Issue #371).
NSApp.windows()[0].contentView().setWantsLayer_(True)
if LINUX:
# On Linux must show before embedding browser, so that handle
# is available (Issue #347).
self.Show()
# In wxPython 3.0 and wxPython 4.0 on Linux handle is
# still not yet available, so must delay embedding browser
# (Issue #349).
if wx.version().startswith("3.") or wx.version().startswith("4."):
wx.CallLater(100, self.embed_browser)
else:
# This works fine in wxPython 2.8 on Linux
self.embed_browser()
else:
self.embed_browser()
self.Show()
def embed_browser(self):
window_info = cef.WindowInfo()
(width, height) = self.browser_panel.GetClientSize().Get()
assert self.browser_panel.GetHandle()
window_info.SetAsChild(self.browser_panel.GetHandle(),
[0, 0, width, height])
self.browser = cef.CreateBrowserSync(window_info,
url="http://127.0.0.1:8000")
self.browser.SetClientHandler(FocusHandler())
def OnSetFocus(self, _):
if not self.browser:
return
if WINDOWS:
cef.WindowUtils.OnSetFocus(self.browser_panel.GetHandle(),
0, 0, 0)
self.browser.SetFocus(True)
def OnSize(self, _):
if not self.browser:
return
if WINDOWS:
cef.WindowUtils.OnSize(self.browser_panel.GetHandle(),
0, 0, 0)
elif LINUX:
(x, y) = (0, 0)
(width, height) = self.browser_panel.GetSize().Get()
self.browser.SetBounds(x, y, width, height)
self.browser.NotifyMoveOrResizeStarted()
def OnClose(self, event):
print("[wxpython.py] OnClose called")
if not self.browser:
# May already be closing, may be called multiple times on Mac
return
if not MAC:
# On Mac shutdown is called in OnClose
cef.Shutdown()
if MAC:
# On Mac things work differently, other steps are required
self.browser.CloseBrowser()
self.clear_browser_references()
self.Destroy()
global g_count_windows
g_count_windows -= 1
if g_count_windows == 0:
cef.Shutdown()
wx.GetApp().ExitMainLoop()
# Call _exit otherwise app exits with code 255 (Issue #162).
# noinspection PyProtectedMember
os._exit(0)
else:
# Calling browser.CloseBrowser() and/or self.Destroy()
# in OnClose may cause app crash on some paltforms in
# some use cases, details in Issue #107.
self.browser.ParentWindowWillClose()
event.Skip()
self.clear_browser_references()
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 FocusHandler(object):
def OnGotFocus(self, browser, **_):
# Temporary fix for focus issues on Linux (Issue #284).
if LINUX:
print("[wxpython.py] FocusHandler.OnGotFocus:"
" keyboard focus fix (Issue #284)")
browser.SetFocus(True)
在主.py在
^{pr2}$在服务器.py在
#!/usr/bin/env python
import os
import django
from django.core.management import call_command
from subprocess import Popen, PIPE
# TODO Clean up and select which process to use to start django
# TODO Note, any method you implement must be able to give some form of log
# TODO FOR debugging ease, You must ensure that you kill the server process
# TODO ON exit from the app itself
def start_server_subprocess():
process = Popen(['python', 'manage.py', 'runserver'], stdout=PIPE, stderr=PIPE)
process.wait()
return process
# This method starts the server in the same thread as the main app
# This leads to freezing, the subprocess method has been chosen
# This is kept for learning purposes!!!
def start_server():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Nets.settings')
django.setup()
try:
call_command("runserver", noreload=True)
except Exception as e:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(e).__name__, e.args)
print(message)
目前没有回答
相关问题 更多 >
编程相关推荐