pygtk+glade实现google translate

 

 

python很好玩。。用了5,6个小时,参考网上的一些例子,简单的写了一个google translate的桌面版,界面和功能都很简陋,只能完成中英,英中翻译。主要是学习下python

 

界面用的glade做的,很方便,画好以后只需要链接好信号就行了,glade配pygtk很方便

不倒100行的源码

 

#!/usr/bin/env python # -*- coding: utf-8 -*- import pygtk import gtk import gtk.glade import urllib import urllib2 import threading import re import sys class trans(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='trans') self.url='http://fanyi.cn.yahoo.com/translate_txt' self.text=None self.trans_in='' self.trans_out='' self.text_out=None self.text_in=None def getText(self,widget): buf=widget.get_buffer() b,e=buf.get_bounds() return buf.get_text(b,e) def setText(self,widget,text=''): buf=widget.get_buffer() buf.set_text(text) widget.set_buffer(buf) def run(self): self.setText(self.text_out,'正在翻译') values={'ei':'UTF-8',/ 'fr':'',/ 'lp':'%s_%s' %(self.trans_in,self.trans_out),/ 'trtext':'%s' %(self.getText(self.text_in).replace('/n','/r/n/r'),)} data=urllib.urlencode(values) request=urllib2.Request(self.url,data) conn=urllib2.urlopen(request) res=conn.read() res=re.findall('<div id="pd" class="pd"> (.{1,})</div>',res) print res res=res[0].replace('<br/>','/n') print res res=res.replace('<dnt> </dnt>','/n') print res self.setText(self.text_out,res) class yahooTrans(): def __init__(self): self.ui_file=sys.path[0]+'/ui.glade' self.widgetTree=gtk.glade.XML(self.ui_file,'window1') dic={"on_exit_clicked":gtk.main_quit,/ "on_window1_destroy":gtk.main_quit,/ "on_to_zh_clicked":self.toZh,/ "on_to_en_clicked":self.toZh} self.widgetTree.signal_autoconnect(dic) def toZh(self,widget): print widget.get_name() t=trans() t.text_in=self.widgetTree.get_widget('text_in') t.text_out=self.widgetTree.get_widget('text_out') if widget.get_name()=='to_zh': t.trans_in='en' t.trans_out='zh' else: t.trans_in='zh' t.trans_out='en' t.setDaemon(True) t.start() def main(self): gtk.main() if __name__=='__main__': gtk.gdk.threads_init() app=yahooTrans() app.main() 

 

 

额,貌似不能上传文件。还有一个glade无法上传

 

你可能感兴趣的:(python,Google,File,Class,buffer,import)