注意:
1 安装pyqt模块
2.python的IDLE默认编码为utf-8
3.去http://fanyi.youdao.com/openapi?path=data-mode,申请一个api key
# -*- coding: utf-8 -*- import sys from PyQt4 import QtGui,QtCore import urllib import json from urllib import urlencode class LH_QWidget(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.first=QtGui.QLineEdit(self) #添加一个文本框 #label1=QtGui.QLabel(‘+‘,self) #self.second=QtGui.QLineEdit(self) #label2=QtGui.QLabel(‘=‘,self) self.third=QtGui.QLineEdit(self) #再添加一个文本框 button=QtGui.QPushButton(‘summit‘,self) #添加一个按钮 grid=QtGui.QGridLayout() #布局 grid.addWidget(self.first,0,0) #grid.addWidget(label1,0,1) #grid.addWidget(self.second ,0,2) #grid.addWidget(label2,0,3) grid.addWidget(self.third,1,0) grid.addWidget(button,2,0) self.resize(300,150) self.setWindowTitle("loster") self.setLayout(grid) self.connect(button,QtCore.SIGNAL(‘clicked()‘),chuli) #按钮的监听,调用函数chuli() def getfirst(self): return self.first.text() def getsecond(self): return self.second.text() def getthird(self,text): self.third.setText(text) def chuli(): url=‘http://fanyi.youdao.com/openapi.do?keyfrom=123licheng&key=1933182090&type=data&doctype=json&version=1.1&q=‘ x=LH_Widget.getfirst() #获取要翻译的文本 #print x x= unicode(x,‘utf-8‘).encode(‘utf-8‘) #把输入转化成utf-8编码 print unicode(x,‘utf-8‘).decode(‘utf-8‘) result=urllib.urlopen(url+x).read() #读入 jsonval=json.loads(result) #获取返回的json结构 print jsonval.values() print ‘---------------‘ print jsonval.keys() print jsonval["translation"][0] LH_Widget.getthird(jsonval["translation"][0]) if __name__=="__main__": app=QtGui.QApplication(sys.argv) LH_Widget=LH_QWidget() LH_Widget.show() sys.exit(app.exec_())