PyQt4 QTextBrowser.append不显示任何输出

时间:2016-06-24 10:36:34

标签: python qt pyqt pyqt4

我刚开始学习PyQt和GUI编程和 我完全从“使用Python和Qt的快速GUI编程:PyQt编程的权威指南”一书中复制了这段代码,它应该显示一个计算表达式的计算器。 当我运行应用程序主窗口显示但没有做任何事情,因为我复制代码形式一个众所周知的pyqt书,这是非常奇怪的。 我正在使用python 3.4.4和pyqt4。这是我从书中复制的代码:

import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Form(QDialog):

    def __init__(self,parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.connect(self.lineedit, SIGNAL("retrunPressed()"),
                     self.updateUi)
        self.setWindowTitle("Calculate")

    def updateUi(self):
        try:
            text= unicode(self.lineedit.text())
            self.browser.append("{0} = <b>{1}</b>".format(text,eval(text)))
        except:
            self.browser.append(
                "<font color=red>%s is invalid!</font>" % text)

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

这些是我得到的错误:

Traceback (most recent call last):

updateUi中的文件“calculator.pyw”,第25行     text = unicode(self.lineedit.text()) NameError:名称'unicode'未定义

在处理上述异常期间,发生了另一个异常:

追踪(最近一次通话):   在updateUi中输入第29行的“calculator.pyw”     “%s无效!” %text) UnboundLocalError:赋值前引用的局部变量'text'

我知道要求其他人调试我的代码并不是一个好主意,但我尽我所能解决它并且没有任何结果。 感谢

1 个答案:

答案 0 :(得分:0)

您的信号名称中应该输入错误

self.connect(self.lineedit, SIGNAL("returnPressed()"),

self.connect(self.lineedit,SIGNAL(&#34; ret ru nPressed()&#34;),

很明显你没有复制好它,看起来那本书是用python2编写的,所以你不需要python3中的unicode函数字符串默认情况下已经是unicode