pico
pico

Reputation: 35

Get event to run when Input in empty

I want an event to run when I type in the input, that works. But only when I type something, not when the field is empty, I want that too

Here's a little template code I wrote that resembles my issue

import PySimpleGUI as sg

list1 = ['a', 'b', 'c']
matches = []
out = []



layout = [
[sg.InputText('', key='-search-', change_submits=True)],
[sg.Listbox(values=out, key='-list-', size=(10,10))]  
]




window = sg.Window('Search', layout, size=(300, 300))



while True:
  event, values = window.read()

  if values['-search-']:
    SearchTerm = values['-search-']
    SearchTerm.replace("['", "")
    SearchTerm.replace("']", "")
    print("Search Term = " + SearchTerm)

    if SearchTerm == "":
      out = list1
      window.Element('-list-').Update(values=list1)
        
    if SearchTerm != "":
      for i in list1:
        if SearchTerm in i:
          if i not in matches:
            matches.append(i)
            outlist = matches
            window.Element('-list-').Update(values=outlist)

  if event == sg.WIN_CLOSED or event == 'Exit':
      break

Upvotes: 0

Views: 392

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

There's re lot of events in event loop, so you have to decide how to check what the event is. For example, if values['-search-']: will be failed it you close the window and values maybe None, then you will get exception TypeError: 'NoneType' object is not subscriptable.

In your event loop, you didn't check the case values['-search-']=='', but just check SearchTerm == "" under the event values['-search-']!=''.

The pattern for event loop maybe like this

while True:

    event, values = window.read()

    if event in (sg.WIN_CLOSED, 'Exit'):
        break

    if event == '-search-':
        if values[event]:
            """ Code if Input element not empty """
        else:
            """ Code if Input element is empty """

window.close()

Upvotes: 1

Related Questions