簡體   English   中英

無法在Python運行時獲取Gtk.ListBox()對象以添加新的Gtk.ListBoxRow()對象

[英]Can't get Gtk.ListBox() object to add new Gtk.ListBoxRow() objects during runtime in Python

我正在通過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.listbox對象的Gtk.ListBox.show_all()函數。 希望這對將來的人有所幫助。

正如@ shaan-repswal已經說過的,您可以在將小部件添加到列表后調用Gtk.ListBox.show_all()

請記住,盡管如果您的行包含要保持不可見的窗口小部件,則必須根據您對窗口小部件的管理方式:

  • 致電your_widget.set_no_show_all(True) ;
  • 將小部件的屬性props.no_show_all設置為True
  • 添加線

    <property name="no_show_all">True</property>

    到Glade文件中小部件的object標簽。

來源: https : //stackoverflow.com/a/29130873/9402438

我最初是在尋找有關C的問題。但是我偶然發現了這個問題,因此C中的各個函數稱為:

gtk_widget_show_all(your_list_box);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM