学了几天的python了,不做项目就是纸上谈兵。所以,打算做个小玩意,调用有道翻译的api,做个图形用户界面的辞典。用户输入单词(中文或英文)点击查询按钮,就将有道翻译api返回的json串进行解释,然后进行显示。
在其中,就可以对python的循环、json处理、urllib、tkinter等有一个综合的复习。
代码很简单,就两个py文件,一个是负责界面显示的(main.py):
#coding=utf-8
from Tkinter import *;
from ttk import *;
from tkMessageBox import showinfo;
import translateutil;
import json;
#制作【卧龙居辞典】的主界面
mainWin = Tk();
#参数属性
width = 500;
height = 300;
word = StringVar();
trans = translateutil.TranslateUtil();
#定义点击了translate方法
def translate():
if str(word.get().lstrip().rstrip())=="":
showinfo("提示","您输入的单词为空!");
else:
rtn = trans.translate(word.get().lstrip().rstrip());
#将json串转换为dict
dataDic = json.loads(rtn,encoding="utf-8");
try:
rtnStr = "释义:";
for elem in dataDic["translation"]:
rtnStr += elem+"\n";
rtnStr += "\n";
rtnStr += "解释:\n";
for elem in dataDic["basic"]["explains"]:
rtnStr += elem+"\n";
except:
#捕获异常
rtnStr = "网络不通或您查询的词无法查到,请确保您的网络联通性及您输入的是正确的单词。";
rtnText.delete(1.0,END);
rtnText.insert(1.0,rtnStr);
#设置标题
mainWin.title("卧龙居辞典V1.0");
#设置大小
mainWin.minsize(width,height);
mainWin.maxsize(width,height);
#各个控件
wordLabel = Label(mainWin,text="单词:");
wordLabel.place(x=10,y=10);
wordEntry = Entry(mainWin,textvariable=word);
wordEntry.place(x=60,y=10,width=250,height=25);
searchBtn = Button(mainWin,text="查询",command=translate);
searchBtn.place(x=330,y=10,width=80,height=25);
#利用state设置rtnText为只读
rtnText = Text(mainWin,foreground="black");
rtnText.place(x=10,y=50,width=480,height=230);
wordEntry.insert(0,"hello");
mainWin.mainloop();
一个负责调用有道翻译的api接口(translateutil.py):
#coding=utf-8
import urllib;
#翻译的类,调用有道线翻译接口
class TranslateUtil(object):
def translate(self,word):
word = {'q':word};
url = '''
http://fanyi.youdao.com/openapi.do?keyfrom=wolongju&key=132468321&type=data&doctype=json&version=1.1&%s
''';
#进行url编码
url = url%(urllib.urlencode(word));
#调用有道在线翻译的接口
rtn = urllib.urlopen(url).read();
return rtn;
pass;