PyGTK - Hello World



使用 PyGTK 建立視窗非常簡單。首先,我們需要在程式碼中匯入 gtk 模組。

import gtk

gtk 模組包含 gtk.Window 類。它的物件構建一個頂級視窗。我們從 gtk.Window 派生一個類。

class PyApp(gtk.Window):

定義建構函式並呼叫 gtk.window 類的 show_all() 方法。

def __init__(self):
   super(PyApp, self).__init__()
   self.show_all()

現在,我們必須宣告此類的物件並透過呼叫其 main() 方法啟動事件迴圈。

PyApp()
gtk.main()

建議我們在父視窗中新增一個標籤 “Hello World”

label = gtk.Label("Hello World")
self.add(label)

以下是顯示 “Hello World” 的完整程式碼:

import gtk

class PyApp(gtk.Window):
   def __init__(self):
      super(PyApp, self).__init__()
      self.set_default_size(300,200)
      self.set_title("Hello World in PyGTK")
      label = gtk.Label("Hello World")
      self.add(label)
      self.show_all()
PyApp()
gtk.main()

上述程式碼的實現將產生以下輸出:

Hello World PyGTK
廣告

© . All rights reserved.