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

时间:2020-10-30 13:01:49

标签: python python-3.x list pysimplegui

我正在运行以下代码并出现此错误。我希望能够上传文件,进行一些处理,然后查看图形。 列表显示为空-但是它应该从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()

1 个答案:

答案 0 :(得分:2)

values['-LISTBOX-']是此列表框中当前选择的项目列表,如果未选择任何内容,它将为空列表。所以你会失败的,

IndexError: list index out of range

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