简体   繁体   中英

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()

This Python+GTK code is giving me the following error:

./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

It also gives me an indentaion error. I am new to Python and GTK. Thanks in advance.

This is most likely how it should be formatted:

#!/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()

I would definitely recommend you to read some basic Python tutorial to at least understand the syntax. Easier to do GUI stuff when you know the basics of the language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM