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

如何解决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 ** 2,'bs',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.,0.2)          # go from 0 to 5 using .2 intervals

    # red dashes,blue squares and green triangles
    plt.plot(t,'b--','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',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',1),justification='c',font=("Arial 10"))],[sg.Text('browse to file:'),sg.Input(size=(40,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-'进行选择,或者检查选择是否为空列表。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?