PySimpleGUI 列表索引超出列表框小部件的范围?

PySimpleGUI list index out of range for listbox widget?

我在运行下面的代码中得到了这个错误。我希望能够上传文件,进行一些处理,然后查看图表。 该列表显示为空 - 但是它应该从 fig_dict 中提取值而不是我认为它正在做的文件浏览值 - 不确定这是为什么?

另一种想法是,这可能是由于 2 'if' 语句造成的。我试过这些但不知道如何解决。

此处错误:

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

我的代码在这里:


    
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()

values['-LISTBOX-']是该列表框中当前选中的项目列表,没有选中时为空列表。所以你会失败,

IndexError: list index out of range

您可以通过事件'-LISTBOX-'来处理选择,或者检查选择是否为空列表。