Python-GTK

  • 4,794 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,794
On Slideshare
0
From Embeds
0
Number of Embeds
6

Actions

Shares
Downloads
129
Comments
0
Likes
5

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Yuren Ju <yurenju@gmail.com> Python-GTK
  • 2. Yuren Ju
    • Yuren's Info Area - http://yureinfore.blogspot.com/
    • 3. Yuren Ju – Linkedin http://tw.linkedin.com/in/yurenju
  • 4. 本份投影片……
    • 假設你學過任何一種程式語言
      • 特別有可能是Java
  • 5. + Python GTK+
  • 6.  
  • 7. Source: TIOBE Software index TIOBE 程式語言社群指標
  • 8. ? Source: &quot;Why?&quot;, Mike Luckovich, Pulitzer-Winning Political Cartoonist (1 of 4) , cc-by-deed
  • 9. 別人怎麼說…
    • 適合初學者,但也適合進階開發者
    • 10. 高度彈性:從大型專案到小型專案都適合使用
    • 11. you can get the job done
    Source: What is Python and Why Python
  • 12. 成功案例
  • 13. 成功案例
    • 三年前……
    • 14. Python 初體驗 - 好吃不黏牙!
    • 15. 要找個簡單的語言寫作業
    • 16. Perl? PHP? Java?
      • Perl: 學過了,想換個口味
      • 17. PHP: 在網頁上寫很麻煩,直接寫成script感覺又有點怪
      • 18. Java: 程式碼超長
        • Print: System.out.println
        • 19. 每個程式都一定要宣告Class
  • 20.  
  • 21. 對我來說的Python優點
    • 短小精簡
    • 22. 快速驗證想法
  • 23. Windows Form wxWidgets Qt GTK+ Swing/AWT Android View/Widget/Layout MFC
  • 24.  
  • 25. Cross Platform crossing the line , Jkönig, CC BY-NC-SA 2.0
  • 26. GTK+ Python C/C++ Perl Ruby C# ... Linux Windows Mac PHP
  • 27. 使用GTK的軟/硬體 Nokia n900
  • 28. Python
  • 29. Start! 將程式碼寫於檔案中 打開終端機直接鍵入程式
  • 30. 打開你的終端機! $ python
  • 31. python command-line
  • 32. print &quot;你好世界!&quot;
  • 33. 數值指定
    • String
      • var = &quot;this is String&quot;
    • Integer
      • var = 1
    • Boolean
      • var = True
    • Float
      • var = 0.1
    不需要宣告形態 String var = &quot;this is String&quot;; int var = 1; boolean var = true; float var = 0.1;
  • 34. Python鐵則
  • 38. Example: agent smith if first == True : print &quot;Mr. Anderson .&quot; else : print &quot;Welcome back, we missed you.&quot; if (first == true) { System.out.println (&quot;Mr. Anderson.&quot;); } else { System.out.println (&quot;Welcome back, we missed you.&quot;); }
  • 39. if first == True : print &quot;Mr. Anderson .&quot; else : print &quot;Welcome back, we missed you.&quot; 4 個空白或是一個 tab 開頭原本是用括號的地方改用冒號 結尾不需要括號
  • 40. list & dict
    • list => 陣列
    • 41. dict => hash table
  • 42. list
    • actors = [&quot;Neo&quot;, &quot;Smith&quot;, &quot;Trinity&quot;, &quot;Oracle&quot;]
    • 43. mixed = [&quot;hi&quot;, &quot;apple&quot;, 0, 0.1, False]
    • 44. print actors[1]
    • 45. actors.append (&quot;Morpheus&quot;)
    • 46. del actors[1]
    • 47. actors.remove (&quot;Oracle&quot;)
  • 48. list (cont.) for a in actors: print a for a in actors[2:]: print a print sorted (actors) del actors[2:]
  • 49. dict person = {&quot;name&quot;: &quot;Yuren Ju&quot;, &quot;website&quot;: &quot;http://yure...&quot;, &quot;birthday&quot;: &quot;yyyy/mm/dd&quot;} print person[&quot;name&quot;] print person[&quot;website&quot;]
  • 50. dict for k in person: print &quot;%s: %s&quot; % (k, person[k]) if person.has_key (&quot;age&quot;): print &quot;no age attribute&quot;
  • 51. function def func (arg1, arg2): #Do something... return ret
  • 52. Editor 將程式碼寫於檔案中
  • 53. 建議
  • 57. Hello-world.py # -*- coding: utf -8 -*- print &quot; 你好世界! &quot;
  • 58. line 1 預設 # -*- coding: utf-8 -*- Python String Byte String Unicode String
  • 59. gedit
  • 60. 實戰?
  • 61. http://ajax.googleapis.com/ajax/services/language/translate? v=1.0&ie=utf8&q=test&langpair=en|zh-tw http://j.mp/dXYwLT
  • 62. #!/usr/bin/env python # -*- coding: utf-8 -*- from urllib2 import urlopen from urllib import urlencode import simplejson import sys def translate (text): sl= &quot;zh-tw&quot; tl= &quot;en&quot; langpair= '%s|%s' %(tl,sl) base_url = 'http://ajax.googleapis.com/ajax/services/language/translate?' data = urlencode({ 'v' : 1.0 , 'ie' : 'UTF8' , 'q' : text, 'langpair' :langpair}) url = base_url+data urlres = urlopen(url) json = simplejson.loads(urlres.read()) result = json[ 'responseData' ][ 'translatedText' ] return result if __name__ == &quot;__main__&quot; : print translate (sys.argv[ 1 ])
  • 63. Class/Object #!/usr/bin/env python # -*- coding: utf-8 -*- class FirstClass : def __init__ (self): self.data = [ &quot;a&quot; , &quot;b&quot; , &quot;c&quot; ] def print_data (self): print self.data if __name__ == &quot;__main__&quot; : f = FirstClass() f.print_data()
  • 64. GTK+
  • 65. #!/usr/bin/env python import pygtk pygtk.require ( '2.0' ) import gtk if __name__ == &quot;__main__&quot; : window = gtk.Window (); window.show () gtk.main ()
  • 66. Event Handler
  • 67. #!/usr/bin/env python import pygtk pygtk.require ( '2.0' ) import gtk def destroy (window): gtk.main_quit () def hello (button): print &quot;Hello World&quot; if __name__ == &quot;__main__&quot; : window = gtk.Window () window.connect ( &quot;destroy&quot; , destroy) window.show () button = gtk.Button ( &quot;hello&quot; ); button.connect ( &quot;clicked&quot; , hello) button.show () window.add (button) gtk.main ()
  • 68. #!/usr/bin/env python import pygtk pygtk.require ( '2.0' ) import gtk class HelloWorld : def __init__ (self): window = gtk.Window () window.connect ( &quot;destroy&quot; , self.destroy) window.show () button = gtk.Button ( &quot;hello&quot; ); button.connect ( &quot;clicked&quot; , self.hello) button.show () window.add (button) self.position = 0 def destroy (self, window): gtk.main_quit () def hello (self, button): print &quot;Hello World, position: %d&quot; % self.position self.position += 1 if __name__ == &quot;__main__&quot; : hello = HelloWorld () gtk.main () Keep state, using class/object
  • 69. Layout. layouts , Kemeny_x, CC BY-NC 2.0
  • 70. GTK+ Layout – box packing
  • 71. HBox VBox
  • 72.  
  • 73. HBox VBox VBox
  • 74. hbox = gtk.HBox() vbox1 = gtk.VBox() vbox2 = gtk.VBox() hbox.pack_start(vbox1) hbox.pack_start(vbox2) pack_start / pack_end
  • 75. window = gtk.Window () hbox = gtk.HBox() vbox1 = gtk.VBox() vbox2 = gtk.VBox() hbox.pack_start(vbox1) hbox.pack_start(vbox2) label = gtk.Label (&quot;Text: &quot;) vbox1.pack_start (label) textview = gtk.TextView () vbox1.pack_start (textview) button_ok = gtk.Button (&quot;OK&quot;) vbox2.pack_end (button_ok) button_cancel = gtk.Button (&quot;Cancel&quot;) vbox2.pack_end (button_cancel) hbox.show_all() window.add(hbox) window.show()
  • 76. layout expand=True fill=True expand=True fill=False expand=False fill=False
  • 77. window = gtk.Window () hbox = gtk.HBox() vbox1 = gtk.VBox() vbox2 = gtk.VBox() hbox.pack_start(vbox1) hbox.pack_start(vbox2, expand=False) label = gtk.Label (&quot;Text: &quot;) label.set_property('xalign', 0.0) textview = gtk.TextView () vbox1.pack_start (label, expand=False) vbox1.pack_start (textview) button_ok = gtk.Button (&quot;OK&quot;) button_cancel = gtk.Button (&quot;Cancel&quot;) vbox2.pack_end (button_ok, expand=False) vbox2.pack_end (button_cancel, expand=False) hbox.show_all() window.add(hbox) window.show()
  • 78. Gtk Builder
  • 79. Gtk Builder builder = gtk.Builder () builder.add_from_file (&quot;layout.glade&quot;) window = builder.get_object (&quot;window1&quot;) window.show ()
  • 80. 翻譯軟體 – GTK 版本
    • 拉UI (glade)
    • 81. 事件分配 (glade)
    • 82. 事件分配 (python)
  • 83. UI Freeze Frozen Moment , drinksmachine, by-nc-nd
  • 84. English 中文 UI Freeze
  • 85. UI Freeze 費時的操作
  • 86. Thread 嘿 Neo, 又是我
  • 87. UI update 費時的操作 Thread
  • 88. def translate (text): ... ... class TransThread (Thread): def __init__ (self, text, obj): self.text = text Thread.__init__(self) def run (self): try : self.result = translate(self.text) except : self.result = &quot;error&quot; Thread
  • 89. Communication? ? UI part Thread part
  • 90. 概念
    • 註冊一個信號(signal)
    • 91. 連接此signal
    • 92. 當Thread結束後射出(emit)此signal
    gtk-gtr2.py
  • 93. 範例
  • 94. TreeView TreeViewColumn CellRendererText ListStore TreeStore View Model
  • 95. Glade ListStore
  • 96. Weather CitiesThread Create WeatherThread Create 產生城市列表 取得城市天氣 load-cities-completed load-weather-completed __init__ selected_city
  • 97. def __init__ (self): self.__gobject_init__() self.builder = gtk.Builder() self.builder.add_from_file ( &quot;weather.glade&quot; ) self.builder.connect_signals(self) win = self.builder.get_object( &quot;window1&quot; ) win.show_all() self.register_signals() self.cities_thread = CitiesThread (self) self.cities_thread.start() self.tree = self.builder.get_object( &quot;treeview_cities&quot; ) col_name = gtk.TreeViewColumn( &quot;city name&quot; ) self.tree.append_column(col_name) cell = gtk.CellRendererText() col_name.pack_start(cell, True ) col_name.add_attribute(cell, 'text' , 0 ) self.tree.connect( &quot;cursor-changed&quot; , self.selected_city) __init__
  • 98. class CitiesThread (Thread): def __init__ (self, obj): self.obj = obj Thread.__init__(self) def run (self): self.cities = pywapi. get_cities_from_google ( 'tw' , 'zh-tw' ) gtk.gdk.threads_enter() self.obj.emit( &quot;load-cities-completed&quot; ) gtk.gdk.threads_leave() CitiesThread
  • 99. WeatherThread class WeatherThread (Thread): def __init__ (self, obj, latitude, longitude): self.obj = obj self.latitude = latitude self.longitude = longitude Thread.__init__(self) def run (self): weather = pywapi.get_weather_from_google( ',,,%s,%s' % (self.latitude, self.longitude), 'zh-tw' ) self.weather = { &quot;condition&quot; : weather[ 'current_conditions' ][ 'condition' ], &quot;humidity&quot; : weather[ 'current_conditions' ][ 'humidity' ], &quot;temp_c&quot; : weather[ 'current_conditions' ][ 'temp_c' ]} gtk.gdk.threads_enter() self.obj.emit( &quot;load-weather-completed&quot; ) gtk.gdk.threads_leave()
  • 100. load-cities-completed def load_cities_completed (self, obj): self.cities = self.cities_thread.cities self.liststore = self.builder.get_object( &quot;cities&quot; ) for city in self.cities: self.liststore.append ([city[ 'name' ], long(city[ 'latitude_e6' ]), long(city[ 'longitude_e6' ])])
  • 101. load-weather-completed def load_weather_completed (self, obj): weather = self.weather_thread.weather self.builder.get_object( &quot;label_temperature&quot; ) .set_markup ( &quot;<span size='xx-large'> 溫度: %s</span>&quot; % weather[ 'temp_c' ]) self.builder.get_object( &quot;label_current&quot; ) .set_label ( &quot; 現在天氣: %s&quot; % weather[ 'condition' ]) self.builder.get_object( &quot;label_humidity&quot; ) .set_label ( &quot; 濕度: %s&quot; % weather[ 'humidity' ])
  • 102. selected_city def selected_city (self, tree): selection = self.tree.get_selection() ( model , iter) = selection.get_selected() name = model.get_value(iter, 0 ) latitude = model.get_value(iter, 1 ) longitude = model.get_value(iter, 2 ) print &quot;%s (%s, %s)&quot; % (name, latitude, longitude) self.weather_thread = WeatherThread(self, latitude, longitude) self.weather_thread.start()
  • 103. gtk-weather.py https://gist.github.com/800513
  • 104. 釣竿
    • Dive Into Python 中文版
    • 105. PyGTK 2.0 Tutorial
    • 106. PyGTK 2.0 Reference Manual
    • 107. google &quot;python gtk <問題關鍵字>&quot;
    • 108. 在stackoverflow.com上面找答案