【发布时间】:2016-12-01 11:32:17
【问题描述】:
我一直在尝试运行此代码 这是错误
File "C:/hari/Academics/python/py programs/gui qt4/book/calculator.py", line 27, in updateUi
text = unicode(self.lineedit.text(),'utf-8')
NameError: name 'unicode' is not defined
代码:
from __future__ import division
from math import *
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Form(QDialog):
def __init__(self,parent =None):
super(Form,self).__init__(parent)
self.browser =QTextBrowser()
self.lineedit =QLineEdit("type an exp")
self.lineedit.selectAll()
layout=QVBoxLayout()
layout.addWidget(self.browser)
layout.addWidget(self.lineedit)
self.setLayout(layout)
self.lineedit.setFocus()
self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateUi)
self.setWindowTitle("Calculate")
def updateUi(self):
try:
text = unicode(self.lineedit.text())
print(type(text))
self.browser.append(text+" = <b>"+eval(text)+"</b>" )
except:
self.browser.append("<font color=red>"+ text + " is invalid</font>")
app=QApplication(sys.argv)
f=Form()
f.show()
app.exec_()
【问题讨论】:
-
顺便说一句:1) 从不使用裸
except:。始终指定要捕获的异常,否则它甚至会捕获KeyboardInterrupt并且还可以轻松隐藏错误。 2) 从不对用户插入的文本调用eval。如果要将文本转换为数字,请使用int(text)或float(text)。如果您想允许任何类型的 literal,请使用ast包中的literal_eval。
标签: pyqt4 python-3.4 python-unicode