Search code examples
pythonlistboxhighlightpysimplegui

Python - SimpleGui - Listbox - After Search I lose the highlight


I've a very simple interface where I have a listbox with my employee names and a Input text where I can put the name to search more quickly.

I've I don't put any text on the input I can select the employee name with a highlight like this:

enter image description here

But if I search for the name (and then I will update this element for the new list with only the names that contains the text that I write) I am not able to get the highlight, as you can see:

enter image description here

My code:

import PySimpleGUI as sg

employees_list = ['John','Pete','Anne','Jack','Golsing']
layout = [[sg.Input(visible=True,size=(15, 1), enable_events=True,key='-input-')]
        ,[sg.Listbox(values=employees_list,size=(15, 3),enable_events=True, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE, key='-employee-')]]

Window = sg.Window('DEV', layout)

while True:
    Event, Values = Window.read()

    if Event == sg.WIN_CLOSED:
        break

    if Values['-input-'] != '':
        search = Values['-input-'].upper()
        new_employees = [x.upper() for x in employees_list if search in x]
        Window.Element('-employee-').Update(values=new_employees, select_mode=sg.LISTBOX_SELECT_MODE_MULTIPLE)

Has anyone been through this? How can I solve it?

Thanks!


Solution

  • You should handle different event here,

        if Values['-input-'] != '':
    

    Here, you will do it if any event generated, so Listbox will be updated when you click Listbox, so selection will be set to none, that's why no item selected or highlighted.

    So the code should be

        if Event == '-input-' and Values['-input-'] != '':
    

    And here you don't recover the listbox to full list when empty input. So maybe you need to handle another case for

        if Event == '-input-' and Values['-input-'] == '':
            # update Listbox with values=employees_list