= glade 3 =
用glade 3可以幫助我們把程式介面畫出來,存檔的副檔名雖為glade,但為xml格式。
細部的格式分libgrade 與 gtkbuilder ,此範例是用 libgrade。
= libgrade =
== ui.glade (libgrade 的xml ) ==
{{{
#!xml
}}}
== python 部份程式碼 ==
{{{
#!python
#!/usr/bin/env python
import pygtk
import gtk
import gtk.glade
...
class Example():
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_XX_clicked":self.toXX,\
"on_OO_clicked":self.toOO}
self.widgetTree.signal_autoconnect(dic)
}}}
=== python範例的完整程式碼 ===
{{{
#!python
#!/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):
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('
(.{1,})
',res)
res=res[0].replace('
','\n')
res=res.replace(' ','\n')
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()
}}}
= GTKBuilder =
* GTKBuilder 為通用格式,libglade也可轉換為此格式
== gtkbuilder 的xml格式 ==
{{{
#!xml
}}}
== python 引用方法 ==
{{{
#!python
import pygtk
pygtk.require("2.0")
import gtk
class TutorialApp(object):
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("tutorial.xml")
builder.connect_signals({ "on_window_destroy" : gtk.main_quit })
self.window = builder.get_object("window")
self.window.show()
if __name__ == "__main__":
app = TutorialApp()
gtk.main()
}}}