Pygtk 简明教程

PyGTK - Hello World

使用 PyGTK 创建窗口非常简单。开始操作之前,首先需要在我们的代码中导入 gtk 模块。

Creating a window using PyGTK is very simple. To proceed, we first need to import the gtk module in our code.

import gtk

gtk 模块包含 gtk.Window 类。它的对象构建一个顶级窗口。我们从 gtk.Window 中派生一个类。

The gtk module contains the gtk.Window class. Its object constructs a toplevel window. We derive a class from gtk.Window.

class PyApp(gtk.Window):

定义构造函数并调用 gtk.window 类的 show_all() 方法。

Define the constructor and call the show_all() method of the gtk.window class.

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

现在我们必须声明此类的对象并通过调用其 main() 方法来启动事件循环。

We now have to declare the object of this class and start an event loop by calling its main() method.

PyApp()
gtk.main()

建议在父窗口中添加一个标签 “Hello World”

It is recommended we add a label “Hello World” in the parent window.

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

以下是显示 “Hello World” 的完整代码:

The following is a complete code to display “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()

以上代码的实现将产生以下输出:

The implementation of the above code will yield the following output −

hello world pygtk