Question

I noticed that the 'gtk' is not defined and I couldn't figure out what it meant despite me managing to import PYGTK when it runs. Below is the code:

import sys

importStatus = False

try:
    from gtk import *
    importStatus = True

except ImportError:
    print "PyGTK module does not exist. Can't launch GUI !"
    print "Please download and install GTK and PyGTK."
    importStatus = False

if importStatus:

    class gtkGUI():

        def __init__(self):
            print "gtkGUI imported"

        def startGUI(self):
            print "GUI Started"
            self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
            return None

Below is the error:

Traceback (most recent call last):
  File "mainGUI.py", line 14, in <module>
    gtk.startGUI()
  File "..../gtkGUI.py", line 25, in startGUI
    gtk.main()
NameError: global name 'gtk' is not defined

How should I solve this error ? Thanks.

Was it helpful?

Solution

You need GTK installed on the system with PyGTK. Usually your import for PyGTK looks something like this:

import pygtk
pygtk.require('2.0')
import gtk

If you look at the PyGTK downloads, you see a reference to installation GTK+. Make sure you do that (I think you're supposed to do it before you install PyGTK, to be fully correct).

OTHER TIPS

gtk isn't defined because you never actually import it as a module. You're using from gtk import * which pulls all the members of the gtk module into the current namespace, rather than importing the module as a whole. So, in line 25, you would have to call Window(WINDOW_TOPLEVEL) and not gtk.Window(gtk.WINDOW_TOPLEVEL).

I would recommend using import gtk rather than from gtk import *.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top