0
votes
#!/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.

1
PyGObject can be used with both GTK+ 2 and GTK+ 3 and you need to choose one. Which one do you want to use? (Note that PyGTK is something entirely different.) And Python has strict indentation rules. I recommend reading both a Python tutorial (this one covers Python 3) and a Python GTK+ tutorial (this covers GTK+ 3, which is the version I recommend). - andlabs
Is that how your code is indented? If not, then could you format it to match the original? - Teemu Risikko
@TeemuRisikko the "It also gives me an indentaion error." implies that that is how their code is indented, further implying they are too new to Python. - andlabs
@andlabs Well not necessarily, the code could have an indentation error even though it is different from the one pasted here. - Teemu Risikko
@TeemuRisikko hm, good point - andlabs

1 Answers

2
votes

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.