在PyGTK/GObject中使用枚举属性
这个教程讲的是在Python中使用GObject,主要介绍了如何使用一种叫做 gobject.TYPE_FLOAT
的属性。
我把它改成了使用一个枚举类型:
import pygtk
pygtk.require('2.0')
import gobject
FUEL_NONE = 0
FUEL_SOME = 1
FUEL_FULL = 2
class Car(gobject.GObject):
__gproperties__ = {
'fuel' : (gobject.TYPE_ENUM, # type
'fuel of the car', # nick name
'amount of fuel that remains in the tank', # description
FUEL_SOME, # default value
gobject.PARAM_READWRITE) # flags
}
# <<rest of demo code>>
...但是当我尝试运行它时,出现了以下错误:
/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py:114: Warning: g_param_spec_enum: assertion `g_enum_get_value (enum_class, default_value) != NULL' failed
type_register(cls, namespace.get('__gtype_name__'))
Traceback (most recent call last):
File "gcar.py", line 9, in <module>
class Car(gobject.GObject):
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 60, in __init__
cls._type_register(cls.__dict__)
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 114, in _type_register
type_register(cls, namespace.get('__gtype_name__'))
TypeError: Error when calling the metaclass bases
could not create param spec for type GEnum (while registering property 'fuel' for GType '__main__+Car')
我漏掉了什么呢?
1 个回答
2
仅仅告诉 __gproperties__
它是一个枚举类型是不够的;你还需要把这个枚举注册到 GObject 类型系统中,然后使用你从中得到的 GType 值,而不是 gobject.TYPE_ENUM
。至少,在 C 语言中是这样做的。我不太确定在 PyGTK 中该怎么做,但可能需要写一个 .defs 文件,然后用 pygobject-codegen-2.0
来处理它。
当然,如果你不是真的需要 GObject 系统理解你枚举的细节,直接把属性设为 gobject.TYPE_INT
,并设置一个最小值和最大值来匹配你的枚举范围,可能会更简单。