使用 python 和 GObject 在空地添加组合框

发布于 2024-12-19 14:05:25 字数 115 浏览 3 评论 0原文

我正在尝试将组合框应用于小型 GTK3 界面,但我无法真正弄清楚如何填充其列表,以及如何将界面的组合框与我的 python 代码连接起来。

有人可以用一个小例子告诉我怎么做吗?剩下的部分我一定能完成。

I'm trying to apply a combobox to a small GTK3 interface, but I can't really figure out how to populate its list, and how to connect the interface's combobox with my python code.

Could someone show me how in a little example? The rest of it I will be able to finish.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绻影浮沉 2024-12-26 14:05:25

ComboBox 与 TextView 或 TreeView 一样,都是将视图(它的外观)与模型(它们包含什么信息)明确分开的小部件。您需要在 Glade 中执行以下操作:

  1. 将组合框添加到 GUI 中的某个位置。
  2. 创建一个将保存数据的 ListStore。将列表存储配置为您需要的任何列(每列都有一个类型)。
  3. 返回组合框,将之前创建的 Liststore 设置为其模型。
  4. 编辑组合框(右键单击,编辑)并添加单元格渲染器。映射该单元格渲染器以显示模型某些列中的数据。
  5. 如果您的数据是静态的,在 Glade 中您可以将行添加到 ListStore。如果您的数据是动态的,您将需要在代码中获取列表存储,然后用与列表存储具有相同类型元素的列表填充它。

我能想到的较小的例子是这样的:

test.glade

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <!-- interface-requires gtk+ 3.0 -->
  <object class="GtkListStore" id="myliststore">
    <columns>
      <!-- column-name code -->
      <column type="gchararray"/>
      <!-- column-name legible -->
      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="window">
    <property name="can_focus">False</property>
    <property name="window_position">center-always</property>
    <property name="default_width">400</property>
    <signal name="destroy" handler="main_quit" swapped="no"/>
    <child>
      <object class="GtkBox" id="box">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkLabel" id="label">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">Best color in the world:</property>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkComboBox" id="mycombobox">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="model">myliststore</property>
            <signal name="changed" handler="combobox_changed" swapped="no"/>
            <child>
              <object class="GtkCellRendererText" id="renderer"/>
              <attributes>
                <attribute name="text">1</attribute>
              </attributes>
            </child>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

test.py

from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):

    def __init__(self):
        # Build GUI
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'test.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')
        self.myliststore = go('myliststore')
        self.mycombobox = go('mycombobox')

        # Initialize interface
        colors = [
            ['#8C1700', 'Redish'],
            ['#008C24', 'Greenish'],
            ['#6B6BEE', 'Blueish'],

        ]
        for c in colors:
            self.myliststore.append(c)
        self.mycombobox.set_active(0)

        # Connect signals
        self.builder.connect_signals(self)

        # Everything is ready
        self.window.show()

    def main_quit(self, widget):
        Gtk.main_quit()

    def combobox_changed(self, widget, data=None):
        model = widget.get_model()
        active = widget.get_active()
        if active >= 0:
            code = model[active][0]
            print('The code of the selected color is {}'.format(code))
        else:
            print('No color selected')

if __name__ == '__main__':
    try:
        gui = MyApp()
        Gtk.main()
    except KeyboardInterrupt:
        pass

亲切的问候

ComboBoxes, like TextViews or TreeViews are widgets that clearly separates the View (what it looks like) from the Model (What info they hold). You need to do in Glade:

  1. Add a Combobox to some place in the GUI.
  2. Create a ListStore that will hold the data. Configure the Liststore to whatever columns you need to have (each column has a type).
  3. Return to the combobox, set the previous created Liststore as it's model.
  4. Edit the combobox (right click, edit) and add a cell renderer. Map that cell renderer to display data from some column of the model.
  5. If your data is static, within Glade you can add rows to your ListStore. If your data is dynamic you will need to get the liststore in your code and then fill it with list that have the same type of elements as your liststore.

The smaller example I could think of is this one:

test.glade

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <!-- interface-requires gtk+ 3.0 -->
  <object class="GtkListStore" id="myliststore">
    <columns>
      <!-- column-name code -->
      <column type="gchararray"/>
      <!-- column-name legible -->
      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="window">
    <property name="can_focus">False</property>
    <property name="window_position">center-always</property>
    <property name="default_width">400</property>
    <signal name="destroy" handler="main_quit" swapped="no"/>
    <child>
      <object class="GtkBox" id="box">
        <property name="visible">True</property>
        <property name="can_focus">False</property>
        <child>
          <object class="GtkLabel" id="label">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="label" translatable="yes">Best color in the world:</property>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <object class="GtkComboBox" id="mycombobox">
            <property name="visible">True</property>
            <property name="can_focus">False</property>
            <property name="model">myliststore</property>
            <signal name="changed" handler="combobox_changed" swapped="no"/>
            <child>
              <object class="GtkCellRendererText" id="renderer"/>
              <attributes>
                <attribute name="text">1</attribute>
              </attributes>
            </child>
          </object>
          <packing>
            <property name="expand">True</property>
            <property name="fill">True</property>
            <property name="position">1</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

test.py

from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):

    def __init__(self):
        # Build GUI
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'test.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')
        self.myliststore = go('myliststore')
        self.mycombobox = go('mycombobox')

        # Initialize interface
        colors = [
            ['#8C1700', 'Redish'],
            ['#008C24', 'Greenish'],
            ['#6B6BEE', 'Blueish'],

        ]
        for c in colors:
            self.myliststore.append(c)
        self.mycombobox.set_active(0)

        # Connect signals
        self.builder.connect_signals(self)

        # Everything is ready
        self.window.show()

    def main_quit(self, widget):
        Gtk.main_quit()

    def combobox_changed(self, widget, data=None):
        model = widget.get_model()
        active = widget.get_active()
        if active >= 0:
            code = model[active][0]
            print('The code of the selected color is {}'.format(code))
        else:
            print('No color selected')

if __name__ == '__main__':
    try:
        gui = MyApp()
        Gtk.main()
    except KeyboardInterrupt:
        pass

Kind regards

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文