1

我注意到没有定义“gtk”,尽管我在运行时设法导入了 PYGTK,但我无法弄清楚它的含义。下面是代码:

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

以下是错误:

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

我应该如何解决这个错误?谢谢。

4

2 回答 2

3

您需要使用 PyGTK 在系统上安装 GTK。通常你的 PyGTK 导入看起来像这样:

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

如果您查看PyGTK 下载,您会看到安装 GTK+ 的参考。确保你这样做(我认为你应该在安装 PyGTK 之前这样做,这是完全正确的)。

于 2011-12-06T04:08:43.717 回答
3

gtk 未定义,因为您实际上从未将其作为模块导入。您正在使用from gtk import *它将 gtk 模块的所有成员拉入当前命名空间,而不是将模块作为一个整体导入。因此,在第 25 行,您必须调用Window(WINDOW_TOPLEVEL)而不是gtk.Window(gtk.WINDOW_TOPLEVEL).

我建议使用import gtk而不是from gtk import *.

于 2011-12-06T09:43:44.990 回答