user11874651
user11874651

Reputation:

PySimpleGUI list index out of range for listbox widget?

I am running the following code and get this error. i want to be able to upload a file, do some processing, then view the graphs. The list is showing up as empty - however it should be pulling values from the fig_dict and not the filebrowse values which I think it is doing - not sure why this is?

The other thought is that could it be due to 2 'if' statements. I've tried these but not sure how to resolve.

Error here:

---> 89    choice = values['-LISTBOX-'][0]                 list)
     90    func = fig_dict[choice]                         
     91    fig = func()                                    
IndexError: list index out of range

My code here:


    
import PySimpleGUI as sg
import time
import os
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.ticker import NullFormatter  # useful for `logit` scale
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
#https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib.py
sg.theme('Dark')

def PyplotSimple():
    import numpy as np
    import matplotlib.pyplot as plt
    t = np.arange(0., 5., 0.2)        
    plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')
    fig = plt.gcf()  # get the figure to show
    return fig

def PyplotSimple2():
    import numpy as np
    import matplotlib.pyplot as plt

    # evenly sampled time .2 intervals
    t = np.arange(0., 5., 0.2)          # go from 0 to 5 using .2 intervals

    # red dashes, blue squares and green triangles
    plt.plot(t, t, 'r--', t, t ** 2, 'b--', t, t ** 3, 'b--')

    fig = plt.gcf()  # get the figure to show
    return fig

def draw_plot():
    plt.plot([0.1, 0.2, 0.5, 0.7])
    fig = plt.gcf()  # get the figure to show
    return fig


def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg
#side='top', fill='both', expand=1
def delete_figure_agg(figure_agg):
    figure_agg.get_tk_widget().forget()
    plt.close('all')


fig_dict = {'One Digit':PyplotSimple, 'Second Digit':PyplotSimple2,'First and Second Digit':draw_plot}

listbox_values = list(fig_dict)
col_listbox = [[sg.Listbox(values=listbox_values, enable_events=True, size=(40, len(listbox_values)), key='-LISTBOX-')],
               [sg.Text()]]

layout= [
    [sg.Text('my new GUI', size=(40,1),justification='c', font=("Arial 10"))],
    [sg.Text('Browse to file:'), sg.Input(size=(40,1), key='input'),sg.FileBrowse (key='filebrowse')],
    [sg.Button('Process' ,bind_return_key=True)], 
    [sg.Col(col_listbox)], 
    [sg.Canvas(size=(100, 100), background_color='white', key= 'CANVAS')], 
    [sg.Exit()]] 

window = sg.Window('MY GUI', layout, grab_anywhere=False, finalize=True)

    
figure_agg = None
# The GUI Event Loop
while True:
    event, values = window.read()
    #print(event, values)                  # helps greatly when debugging
    if event in (sg.WIN_CLOSED, 'Exit'):           
        break
    if event == 'Process':
        inputfile = values['filebrowse']
        #my function here
        sg.popup('Complete - view graphs',button_color=('#ffffff','#797979'))

    if figure_agg:
        
        delete_figure_agg(figure_agg)
    choice = values['-LISTBOX-'][0]                 # get first listbox item chosen (returned as a list)
    func = fig_dict[choice]                         # get function to call from the dictionary
    fig = func()                                    # call function to get the figure
    figure_agg = draw_figure(window['CANVAS'].TKCanvas, fig)   
window.close()

Upvotes: 0

Views: 1177

Answers (1)

Jason Yang
Jason Yang

Reputation: 13061

values['-LISTBOX-'] is the list of items currently selected in this listbox, and it will be empty list when nothing selected. So you will get a failure,

IndexError: list index out of range

You can handle it by event '-LISTBOX-' for selection, or check if the selection is empty list.

Upvotes: 1

Related Questions