PyGobject 错误

PyGobject error

#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Gtk
class ourwindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="My Hello World Program")
Gtk.Window.set_default_size(self, 400,325)
Gtk.Window.set_position(self, Gtk.WindowPosition.CENTER)
button1 = Gtk.Button("Hello, World!")
button1.connect("clicked", self.whenbutton1_clicked)
self.add(button1)
def whenbutton1_clicked(self, button):
print "Hello, World!"
window = ourwindow()        
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()

这个 Python+GTK 代码给我以下错误:

./pygtk.py
./pygtk.py:3: PyGIWarning: Gtk was imported without specifying a version      first. Use gi.require_version('Gtk', '3.0') before import to ensure that the right version gets loaded.
 from gi.repository import Gtk
 Traceback (most recent call last):
 File "./pygtk.py", line 4, in <module>
 class ourwindow(Gtk.Window):
 File "./pygtk.py", line 10, in ourwindow
 button1.connect("clicked", self.whenbutton1_clicked)
 NameError: name 'self' is not defined

它也给我一个缩进错误。 我是 Python 和 GTK 的新手。 提前致谢。

最有可能的格式是:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from gi.repository import Gtk

class ourwindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="My Hello World Program")
        Gtk.Window.set_default_size(self, 400,325)
        Gtk.Window.set_position(self, Gtk.WindowPosition.CENTER)
        button1 = Gtk.Button("Hello, World!")
        button1.connect("clicked", self.whenbutton1_clicked)
        self.add(button1)

    def whenbutton1_clicked(self, button):
        print "Hello, World!"

window = ourwindow()        
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()

我肯定会建议您阅读一些基本的 Python 教程,以至少了解语法。当您了解该语言的基础知识时,可以更轻松地执行 GUI 操作。