2016-06-24 107 views
0

我刚刚开始学习PyQt和GUI编程,并且我从012页的“用Python和Qt进行快速GUI编程:PyQt编程权威指南”应该显示一个计算器来计算表达式。 当我运行应用程序主窗口出现,但没有做任何事情,因为我复制代码形式一个众所周知的pyqt书,这是非常奇怪的。 我使用python的3.4.4和PyQt4的。这是我从书抄代码:PyQt4 QTextBrowser.append Does not not any output

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): 

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

在处理上述例外的,另一个异常:

回溯(最近呼叫最后): 文件“calculator.pyw”,第29行,更新UI “%s无效!” %text) UnboundLocalError:分配之前引用的局部变量“文本”

我知道不要求其他人调试我的代码,但我尽我所能,并且没有出现。 感谢

回答

0

您的信号名称的错字,应该

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

self.connect(self.lineedit,SIGNAL( “RET nPressed()”),

所以显然你没有复制它,也似乎书是用python2编写的,所以你不需要python3中的unicode函数字符串默认情况下是unicode

+0

谢谢你。我的问题解决了unicode和信号change.can你推荐我一本更新的书,涵盖pyqt5和python3? –

+0

不幸的是,我不知道有任何完整的pyqt5电子书,但有很多教程和'Qt4'的概念仍然存在,但看看这个链接http://stackoverflow.com/questions/20996193/is-there-a-tutorial-specific-for-pyqt5 – danidee

+0

也不会忘记接受我的答案,如果它为你工作:) – danidee