Search code examples
pythonpython-3.xuser-interfacegtkpygtk

Select a choice from a python Gtk List and store it in a variable


I am making a menu of a GUI using python Gtk. I have made a Gtk list and depict it in a Gtk Assistant windows (which has back and next buttons). I would like to store in a variable the selected option from the list after next button is pressed and I have not found a way. The sample below is about Gtk.Assistant window and its first page.

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

IMAGE_FOLDER = "images/"
count = 1
image_list = []

while True:
    cur_image = os.popen("ls "+IMAGE_FOLDER+" | sed -n "+str(count)+"p | tr -d '\n'").read()
    if not cur_image:
         break
    image_list.append([cur_image])
    print("image list =", image_list)
    count+=1

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)

    self.image= Gtk.Image()
    self.image.set_from_file('./logo.png')

    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")
    menu = Gtk.ListStore(str)
    for choice in range(len(image_list)):
        print(choice)

        menu.append(image_list[choice])
    menutreeview1 = Gtk.TreeView(menu)
    renderer1 = Gtk.CellRendererText()

    column1 = Gtk.TreeViewColumn("Select image for the installation", renderer1, text=0)
    menutreeview1.append_column(column1)

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

assistant = Assistant()
assistant.show_all()

Gtk.main()

Solution

  • You can use:

    selectedtext = None
    treeselection = self.menutreeview1.get_selection()
    (treemodel, selectediter) = treeselection.get_selected()
    if selectediter is not None:
      selectedtext = treemodel[selectediter][0]
    

    Remember to make menutreeview1 a data member and set its selection mode to single:

    self.menutreeview1 = Gtk.TreeView(menu)
    self.menutreeview1.get_selection().set_mode(Gtk.SelectionMode.SINGLE)