环境:
-
虽然我知道我需要用来更新标签文本的方法(label.set_text(“string”)),但我在python代码中获取标签对象时遇到了麻烦。
以下是我的代码:
#!/usr/bin/python
# Filename: HelloPython.py
# Author: Andrew Hefley Carpenter
# Date: 18 August 2010
import sys
import gtk
class HelloPython:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("HelloPython.xml")
self.window = builder.get_object("window")
builder.connect_signals(self)
def on_button1_clicked(self, widget):
print "Hello World!"
widget.set_label("Hello World!")
#I'd like to update
if __name__ == "__main__":
editor = HelloPython()
editor.window.show()
gtk.main()
结束目标:我想在回复“对象Y”(在本例中为button1)之后使用它的set_text方法更新“对象X”,由“on_button1_clicked”处理
答案 0 :(得分:4)
on_button1_clicked的widget参数是gtk.Button,而不是gtk.Label。 gtk.Button有一个方便的api方法叫做set_label()。
这只适用于Gtk.Button的孩子是gtk.Label。这是在Glade-3中创建新按钮时的默认设置,但如果您更改了按钮的内容,则无法使用,并且您需要引用gtk.Label小部件本身。
EDIT(更新标签的代码):
class HelloPython:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("HelloPython.xml")
self.window = builder.get_object("window")
self.label = builder.get_object("label1") # get reference to the label
builder.connect_signals(self)
def on_button1_clicked(self, widget):
#widget.set_label("Hello World!") this would set the button's text
self.label.set_text("Hello World!") # this sets the label's text