代碼如下:
require 'net/http'
require 'tk'
require 'logger'
#設定代理
$proxy_addr='x.x.x.x'
$proxy_port='80'
class googletranslate
def initialize(url)
@log = logger.new("translate.log")
@log.level = logger::warn
@url=url
ph={'padx'=>50,'pady'=>10}
root=tkroot.new{ title 'google 翻譯程式'}
top=tkframe.new(root) {background "white"}
#checkbutton,用于選擇翻譯類别
checked=tkvariable.new
tkcheckbutton.new(top) do
text 'cn-en'
variable checked
pack({'padx'=>8,'pady'=>10})
end
tklabel.new(top){ text 'enter text:';pack(ph)}
@text=tkvariable.new
@result=tkvariable.new
tkentry.new(top,'textvariable'=>@text,'width'=>40).pack(ph)
pig_b=tkbutton.new(top){text '翻譯';pack ph}
#翻譯按鈕事件
pig_b.command{ translate(checked.value) }
tklabel.new(top){ text 'translate result:';pack(ph)}
tkentry.new(top,'textvariable'=>@result,'width'=>40).pack(ph)
pig_a=tkbutton.new(top) do
text 'exit'
pack ph
command {exit}
end
top.pack('fill'=>'both','side'=>'top')
end
def translate(checked)
langpair='en|zh-cn'
langpair='zh-cn|en' if checked=='1'
#開一個新線程處理
thread.new do
begin
response=net::http.proxy($proxy_addr,$proxy_port).post_form(uri.parse(@url),
{'text'=>@text.value,'langpair'=>langpair})
response.body =~ /<div id=result_box dir=ltr>(.*?)<\/div>/
@result.value=$1
rescue exception=>e
@log.error(e)
end
end
googletranslate.new("http://translate.google.com/translate_t")
tk.mainloop
文章轉自莊周夢蝶 ,原文釋出時間2007-09-04