如何从类中的回调函数添加新的小部件?例如,我有一个Gtk.Box和Gtk.Button,我想将Gtk.Label从连接到按钮单击的回调函数添加到Gtk.Box。 (此代码无效)
import gi
import os
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk, GObject, Gio
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Delete Screenshots")
self.main_grid = Gtk.Grid()
self.main_grid.set_row_homogeneous(True)
self.add(self.main_grid)
self.screen_label = Gtk.Label()
self.screen_label.set_text("Test Label")
self.screen_label2 = Gtk.Label()
self.screen_label2.set_text("Test Label2")
self.label_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.label_box.homogeneous = True
self.button_search = Gtk.Button(label="Search")
self.button_search.connect("clicked", self.on_button_search_clicked)
self.button_delete = Gtk.Button(label="Delete")
self.button_delete.connect("clicked", self.on_button_delete_clicked)
self.main_grid.add(self.button_search);
self.main_grid.attach(self.button_delete, 1, 0, 1, 1);
self.main_grid.attach(self.label_box, 0, 1, 1, 1)
def on_button_search_clicked(self, widget):
self.label_box.pack_start(self.screen_label, True, True, 0)
def on_button_delete_clicked(self, widget):
print("Delete")
win = MainWindow()
win.set_default_size(50, 30)
win.set_position(Gtk.WindowPosition.CENTER_ALWAYS)
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
如何通过on_button_search_clicked向label_box添加内容?
答案 0 :(得分:0)
您的代码基本上是正确的。但是,需要通过在它们上调用show()
或在父窗口小部件上调用show_all()
来显示所有窗口小部件。在您的代码中,在show_all()
实例上调用MainWindow
。那时,您在回调中添加的窗口小部件未附加到窗口或其任何子级。因此,它将不会包含在show_all()
调用中。
要解决此问题,只需在回调中的标签上调用show()
:
...
def on_button_search_clicked(self, widget):
self.label_box.pack_start(self.screen_label, True, True, 0)
self.screen_label.show()
...