【问题标题】:PyGobject errorPyGobject 错误
【发布时间】:2016-09-23 13:06:20
【问题描述】:
#!/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 的新手。 提前致谢。

【问题讨论】:

  • PyGObject 可以与 GTK+ 2 和 GTK+ 3 一起使用,您需要选择一个。你想用哪一个? (请注意,PyGTK 是完全不同的东西。)Python 有严格的缩进规则。我建议阅读a Python tutorial(这个涵盖Python 3)和Python GTK+ tutorial(这个涵盖GTK+ 3,这是我推荐的版本)。
  • 你的代码是这样缩进的吗?如果不是,那你能把它格式化成与原来的一致吗?
  • @TeemuRisikko “它也给了我一个缩进错误。”暗示他们的代码就是这样缩进的,进一步暗示他们对 Python 来说太新了。
  • @andlabs 不一定,代码可能有缩进错误,即使它与此处粘贴的不同。
  • @TeemuRisikko 嗯,好点

标签: python gtk pygobject


【解决方案1】:

这很可能是它的格式:

#!/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 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多