【问题标题】:Tkinter window, button and display HTML page in PyQt5PyQt5中的Tkinter窗口、按钮和显示HTML页面
【发布时间】:2021-01-20 06:25:28
【问题描述】:

大家早上好/晚上好,我正在尝试使用 Tkinter 创建 GUI,并在单击 Tkinter 按钮后使用 PyQt5.QtWebEngineWidgets 显示 HTML 页面。一切正常,但关闭 PyQt HTML 页面并再次单击按钮后 - 一切都冻结并且内核正在重新启动。

我把最重要的代码贴在下面:

import tkinter as tk    

window = tk.Tk()
btn = tk.Button(window, text = "Click me!",  command = display_HTML)
btn.place(relx=0.2, rely=0.6, anchor="center")
window.mainloop()

和display_HTML函数:

from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl
import sys

def display_HTML():
    app = QApplication(sys.argv)
    
    br = QWebEngineView()
    file_path = r"C:\....html"
    local_url = QUrl.fromLocalFile(file_path)
    br.load(local_url)
    
    br.setWindowTitle("HTML content")
    br.show()
    
    app.exec_()       

您能帮我解决这个问题吗?非常感谢。

【问题讨论】:

  • 也许尝试创建另一种 QApplication 方式?

标签: python html button pyqt5 display


【解决方案1】:

注意:当我按下按钮并启动 HTML 查看器时,我观察到包含该按钮的窗口冻结(要检查这一点,请尝试更改该窗口的大小),并且当再次启动 HTML 查看器时, 分段错误(核心转储)

2 个事件循环(tkinter 和 Qt)不能共存于同一个线程,因为它们被阻塞了,因此一个可能的解决方案是在新进程中启动 Qt:

import tkinter as tk
from multiprocessing import Process

window = tk.Tk()
btn = tk.Button(
    window, text="Click me!", command=lambda *args: Process(target=display_HTML).start()
)
btn.place(relx=0.2, rely=0.6, anchor="center")
window.mainloop()

【讨论】:

  • 在我的情况下(Spyder IDE),按下按钮后没有 HTML 视图。我使用你的代码和我的函数 display_HTML() - 你认为这可能是一个 IDE 问题吗?
  • @MartinDomino 可能是的,我不使用任何 IDE 来运行脚本(并且 IDE 不用于生产)。尝试从控制台运行脚本,如果它有效,那么它是一个 spyder 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
  • 2021-08-01
相关资源
最近更新 更多