在大多数 pygtk 小部件页面中,它们包含称为“属性”、“属性”和“样式属性”的部分。如何更改这些属性和属性?
4 回答
更改属性的三种方法:
正如在 zheoffec 的回答中一样,使用该
set_property()函数(或set_style_property()用于样式属性。)这个函数在 Python 中实际上不是必需的,但它是为了完整性而存在的,因为它是 C API 的一部分。使用
props属性。您在文档中找到的任何属性都可以通过此属性访问。例如,btn1.props.label = 'StackOverflow'和btn1.props.use_underline = False。按照 frb 的建议使用 getter 和 setter 函数。这些也只是因为它们是 C API 的一部分而存在,但有些人更喜欢它们而不是
props属性。此外,不能保证任何特定属性都具有 getter 和 setter 函数!通常在精心设计的 C API 中它们会出现,但这不是必需的。
对于样式属性,我相信唯一的选择是#1。对于“属性”,这些只是 Python 属性。要访问该allocation属性,请使用btn1.allocation.
要在 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'>
    在 PyGTK 中,GtkWidget是所有其他小部件类(包括您可能自己制作的小部件类)继承的基类。
就设置属性而言,您可能注意到您不能直接设置它们:
btn1.label = "StackOverflow"
在 PyGTK 中,您需要在属性名称前加上 前缀set_,如下所示:
btn1.set_label("StackOverflow")
如果-属性名称中有 a,例如 with use-underline,请将它们转换为下划线,例如set_use_underline. 我想说的是,我不认为 getter 和 setter 的这种使用是非常 Pythonic 的。
这是一个完整的工作程序,取自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()
    您可以使用该Gtk.Widget.set_property(property, value)方法更改 Widget 属性。property应该是一个字符串。