Skip to main content
 首页 » 编程设计

python之无法获取 Gtk.ListBox() 对象以在运行时在 Python 中添加新的 Gtk.ListBoxRow() 对象

2025年05月04日29xiaohuochai

我通过 Python 3.4 在 Windows 10 上使用 Gtk 3.18。我编写了以下脚本来按下一个按钮,将一个新的 Gtk.ListBoxRow() 添加到我的 MyWindow 类中的 self.listbox 中。它发生在函数 add_item(self, whatevs) 中。

我清楚地提到那里

self.listbox.add(row) 

那为什么还是不行呢?当我按下“添加项目”按钮时,该功能被调用。但是列表没有得到另一行。为什么这么有想法?

没有任何反应。甚至没有显示任何错误。有人可以告诉我我在这里做错了什么吗?感谢您的帮助。

import gi 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 
 
class MyWindow(Gtk.Window): 
    def __init__(self): 
        Gtk.Window.__init__(self, title = "Win win win") 
        self.set_border_width(3) 
        self.set_default_size(300, 250) 
 
        box = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 6) 
        self.add(box) 
 
        self.listbox = Gtk.ListBox() 
        self.listbox.set_selection_mode(Gtk.SelectionMode.SINGLE) 
 
        box.pack_start(self.listbox, True, True, 0) 
 
        row = Gtk.ListBoxRow() 
        hbox = Gtk.Box() 
        row.add(hbox) 
        hbox.pack_start(Gtk.Label("Here is an Item"), True, True, 0) 
        self.listbox.add(row) 
 
        hbox = Gtk.Box() 
 
        button_add_item = Gtk.Button(label = "Add Item", valign = Gtk.Align.CENTER) 
        button_add_item.connect("clicked", self.add_item) 
        hbox.pack_start(button_add_item, True, True, 0) 
 
        button_remove_item = Gtk.Button(label = "Remove Item", valign = Gtk.Align.CENTER) 
        button_remove_item.connect("clicked", self.remove_item) 
        hbox.pack_start(button_remove_item, True, True, 0) 
 
        box.pack_start(hbox, False, True, 0) 
 
    def add_item(self, whatevs): 
        row = Gtk.ListBoxRow() 
        hbox = Gtk.Box() 
        row.add(hbox) 
        item_label = Gtk.Label("Here is another Item") 
        hbox.pack_start(item_label, True, True,0) 
        self.listbox.add(row) 
 
    def remove_item(self, whatevs): 
        self.listbox.remove(self.listbox.remove.get_row_at_y(-1)) 
 
win = MyWindow() 
win.connect('delete-event', Gtk.main_quit) 
win.show_all() 
Gtk.main() 

顺便说一句,有人能告诉我为什么我必须在按钮的“已连接”功能中包含另一个参数,即“self”以外的参数吗?知道如何使用它们吗?

请您参考如下方法:

我发现了问题所在。我应该在我的程序中使用 self.listbox 对象的 Gtk.ListBox.show_all() 函数。希望这对以后的人有帮助。