我一直在尝试运行此代码 这是错误 在updateUi中输入文件“C:/ hari / Academics / python / py programs / gui qt4 / book / calculator.py”,第27行 text = unicode(self.lineedit.text(),'utf-8') NameError:名称'unicode'未定义
代码:
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_()
答案 0 :(得分:2)
在python 3中,默认情况下是unicode。
删除unicode
功能,替换为str
。
https://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit
就像Bakuriu在评论中所说的那样,除了:
之外,永远不要使用裸露体型:
except Exception as e:
print("Problem "+repr(e))
# the line below requires some HTML normalization or resulting
# html could be incorrect
import re
ne = re.sub("[^\w]"," ",str(e))
self.browser.append("<font color=red>"+ne+"</font>")
现在您显示了真实/下一个异常。
答案 1 :(得分:0)
希望您使用的是Python 3,所以请替换
带有Unicode
函数的 Str
函数。
def updateUi(self):
try:
text = str(self.lineedit.text()) ##replaced here