网页幻灯片(python)

时间:2016-07-22 10:04:00

标签: python pyqt4 urllib sys

我试图在Python中制作一个简单的幻灯片,以查看0.html,1.html和2.html,它们之间有3秒的延迟。

下面的脚本在3秒内显示0.html,然后我得到一个"分段错误(核心转储)"错误。有什么想法吗?

到目前为止我的代码:

#!/usr/bin/python
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import urllib


class Window(QWidget):

    def __init__(self, url, dur):
        super(Window, self).__init__()
        view = QWebView(self)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(view)

        html = urllib.urlopen(url).read()       
        view.setHtml(html)
        QTimer.singleShot(dur * 1000, self.close)


def playWidget(url, dur):
        app = QApplication(sys.argv)
        window = Window(url, dur)
        window.showFullScreen()
        app.exec_()

x = 0
while (x < 3):
    page = "%s.html" % x
    playWidget(page , 3)
    x = x + 1

1 个答案:

答案 0 :(得分:0)

您不能创建多个QApplication,这就是您的示例转储核心的原因。但无论如何,如果您的程序需要创建一个全新的浏览器窗口来显示每个页面,那么这是一个相当糟糕的设计。你应该做的是将每个新页面加载到同一个浏览器中。

这是重写你的脚本:

#!/usr/bin/python
import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
import urllib


class Window(QWidget):   
    def __init__(self, urls, dur):
        super(Window, self).__init__()
        self.urls = urls
        self.duration = dur * 1000
        self.view = QWebView(self)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.view)
        self.nextUrl()

    def nextUrl(self):
        if self.urls:
            url = self.urls.pop(0)
            html = urllib.urlopen(url).read()
            self.view.setHtml(html)
            QTimer.singleShot(self.duration, self.nextUrl)
        else:
            self.close()

def playWidget(urls, dur):
    app = QApplication(sys.argv)
    window = Window(urls, dur)
    window.showFullScreen()
    app.exec_()

urls = [
    'https://tools.ietf.org/html/rfc20',
    'https://tools.ietf.org/html/rfc768',
    'https://tools.ietf.org/html/rfc791',
    ]

playWidget(urls, 3)