You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Gtk Assistant中存储列表选中项至变量

解决Gtk Assistant中获取TreeView选中项的问题

我明白你想要在点击Gtk Assistant的"下一步"按钮后,把列表里的选中项存到变量里。咱们来一步步修改你的代码实现这个功能:

首先,你需要把TreeView和ListStore改成类的实例属性,这样在其他方法里能访问到它们。然后,我们可以利用Gtk Assistant的prepare信号——这个信号会在页面即将显示时触发,刚好可以在切换到下一页前获取第一页的选中项。

下面是修改后的完整代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import os

IMAGE_FOLDER = "images/"
image_list = []

# 更优雅地读取图片文件夹里的文件,替代原来的os.popen方法
try:
    for filename in os.listdir(IMAGE_FOLDER):
        if os.path.isfile(os.path.join(IMAGE_FOLDER, filename)):
            image_list.append([filename])
except FileNotFoundError:
    print(f"Error: 文件夹 {IMAGE_FOLDER} 不存在")

class Assistant(Gtk.Assistant):
    def __init__(self):
        Gtk.Assistant.__init__(self)
        self.set_title("Image Installer")
        self.set_default_size(400, 200)
        self.connect("cancel", self.on_cancel_clicked)
        self.connect("close", self.on_close_clicked)
        self.connect("apply", self.on_apply_clicked)
        # 添加prepare信号连接,用于处理页面切换时的逻辑
        self.connect("prepare", self.on_prepare_page)
        
        # 存储选中的图片文件名
        self.selected_image = None

        self.image= Gtk.Image()
        try:
            self.image.set_from_file('./logo.png')
        except Exception as e:
            print(f"Error loading logo: {e}")

        # 第一页:图片选择页
        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.append_page(box)
        self.set_page_type(box, Gtk.AssistantPageType.INTRO)
        self.set_page_title(box, "Image selection")

        # 将ListStore和TreeView设为类属性
        self.menu_store = Gtk.ListStore(str)
        for choice in image_list:
            self.menu_store.append(choice)
        
        self.image_treeview = Gtk.TreeView(self.menu_store)
        renderer1 = Gtk.CellRendererText()
        column1 = Gtk.TreeViewColumn("Select image for the installation", renderer1, text=0)
        self.image_treeview.append_column(column1)
        # 设置TreeView为单选模式(默认就是单选,这里显式设置更清晰)
        self.image_treeview.get_selection().set_mode(Gtk.SelectionMode.SINGLE)

        box.pack_start(self.image_treeview, True, True, 0)
        box.pack_start(self.image, True, True, 0)
        self.set_page_complete(box, True)

        # 可以添加第二页示例,比如确认页
        confirm_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        confirm_label = Gtk.Label()
        self.confirm_label = confirm_label
        confirm_box.pack_start(confirm_label, True, True, 10)
        self.append_page(confirm_box)
        self.set_page_type(confirm_box, Gtk.AssistantPageType.CONFIRM)
        self.set_page_title(confirm_box, "Confirm Selection")

    def on_prepare_page(self, assistant, page):
        # 判断当前准备显示的是第二页(确认页),此时获取第一页的选中项
        current_page_idx = assistant.get_current_page()
        if current_page_idx == 1:  # 第二页的索引是1(第一页是0)
            selection = self.image_treeview.get_selection()
            model, tree_iter = selection.get_selected()
            if tree_iter is not None:
                # 从模型中获取选中的文件名
                self.selected_image = model[tree_iter][0]
                self.confirm_label.set_text(f"你选中的图片是:{self.selected_image}")
                # 标记确认页为完成,允许点击下一步/应用
                self.set_page_complete(page, True)
            else:
                self.confirm_label.set_text("请先选择一张图片!")
                self.set_page_complete(page, False)

    def on_cancel_clicked(self, assistant):
        Gtk.main_quit()

    def on_close_clicked(self, assistant):
        Gtk.main_quit()

    def on_apply_clicked(self, assistant):
        # 在这里可以使用存储的选中项做后续操作
        if self.selected_image:
            print(f"开始安装图片:{self.selected_image}")
        Gtk.main_quit()

assistant = Assistant()
assistant.show_all()
Gtk.main()

关键修改点说明:

  • 将ListStore和TreeView改为类属性:这样在on_prepare_page方法里能直接访问到它们,方便获取选中项。
  • 连接prepare信号:这个信号会在每个页面即将显示前触发,我们在这里判断如果是要显示第二页,就去第一页的TreeView里拿选中项。
  • 获取选中项的逻辑:通过TreeView.get_selection()获取选择对象,再用get_selected()得到选中的模型和迭代器,最后从模型中提取数据。
  • 添加了第二页示例:用来展示选中的图片,同时演示如何控制页面的完成状态(如果没选图片,就不让下一步)。
  • 优化了图片文件夹读取逻辑:用os.listdir替代os.popen,更安全可靠,还处理了文件夹不存在的异常。

现在,当你点击"下一步"到确认页时,选中的图片文件名就会被存在self.selected_image变量里,之后你可以在on_apply_clicked或者其他方法里使用这个变量做后续操作。

内容的提问来源于stack exchange,提问作者zograpo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 09:03:15