编辑GtkWidget属性
在大多数pygtk小部件页面中,都会有一些叫做“属性”、“特性”和“样式特性”的部分。我该如何更改这些属性和特性呢?
4 个回答
在PyGTK中,GtkWidget
是所有其他小部件类的基础类,包括你自己可能会创建的小部件。
关于设置属性,你可能注意到不能直接设置它们:
btn1.label = "StackOverflow"
在PyGTK中,你需要在属性名称前加上set_
,像这样:
btn1.set_label("StackOverflow")
如果属性名称中有-
,比如use-underline
,你需要把它们改成下划线,变成set_use_underline
。我想说的是,我觉得这种使用获取器和设置器的方式不太符合Python的风格。
这里有一个完整的工作程序,来自于ZetCode教程,并进行了修改。
import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_title("Buttons")
self.set_size_request(250, 200)
self.set_position(gtk.WIN_POS_CENTER)
btn1 = gtk.Button("Button")
btn1.set_label("StackOverflow")
btn1.set_use_underline(False)
fixed = gtk.Fixed()
fixed.put(btn1, 20, 30)
self.connect("destroy", gtk.main_quit)
self.add(fixed)
self.show_all()
PyApp()
gtk.main()
要获取所有的组件,可以查看它们的 widget.pros 列表:
button = gtk.Button()
for pspec in button3.props:
print pspec
#print button3.get_property(pspec.name)
输出结果:
<GParamObject 'related-action'>
<GParamBoolean 'use-action-appearance'>
<GParamPointer 'user-data'>
<GParamString 'name'>
<GParamObject 'parent'>
<GParamInt 'width-request'>
<GParamInt 'height-request'>
<GParamBoolean 'visible'>
<GParamBoolean 'sensitive'>
<GParamBoolean 'app-paintable'>
<GParamBoolean 'can-focus'>
<GParamBoolean 'has-focus'>
<GParamBoolean 'is-focus'>
<GParamBoolean 'can-default'>
<GParamBoolean 'has-default'>
<GParamBoolean 'receives-default'>
<GParamBoolean 'composite-child'>
<GParamObject 'style'>
<GParamFlags 'events'>
<GParamEnum 'extension-events'>
<GParamBoolean 'no-show-all'>
<GParamBoolean 'has-tooltip'>
<GParamString 'tooltip-markup'>
<GParamString 'tooltip-text'>
<GParamObject 'window'>
<GParamBoolean 'double-buffered'>
<GParamUInt 'border-width'>
<GParamEnum 'resize-mode'>
<GParamObject 'child'>
<GParamString 'label'>
<GParamObject 'image'>
<GParamEnum 'relief'>
<GParamBoolean 'use-underline'>
<GParamBoolean 'use-stock'>
<GParamBoolean 'focus-on-click'>
<GParamFloat 'xalign'>
<GParamFloat 'yalign'>
<GParamEnum 'image-position'>
有三种方法可以改变属性:
就像zheoffec的回答中提到的,使用
set_property()
函数(如果是样式属性,可以用set_style_property()
)。其实在Python中这个函数并不是必须的,但为了完整性,它还是存在的,因为它是C语言接口的一部分。使用
props
属性。你在文档中找到的任何属性都可以通过这个属性来访问。例如,btn1.props.label = 'StackOverflow'
和btn1.props.use_underline = False
。使用获取和设置函数,正如frb所建议的。这些函数也是因为它们是C语言接口的一部分而存在,但有些人更喜欢用它们而不是
props
属性。另外,并不是所有的属性都有获取和设置函数!通常在设计良好的C语言接口中会有这些函数,但这并不是必须的。
对于样式属性,我认为唯一的选择是第一种。至于“属性”,这些其实就是Python的属性。要访问 allocation
属性,可以使用 btn1.allocation
。