索引在范围内时如何解决索引超出范围

时间:2020-07-02 15:51:30

标签: python kivy kivy-language

当我运行该程序时,它说“ self.buttons [1] .bind(on_press = self.on_click)IndexError:列表索引超出范围”,但我要访问的元素仍在范围内。我该如何解决?

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color

class LandingScreen(BoxLayout):
    def __init__(self, **kwargs):
        super(LandingScreen, self).__init__(**kwargs)

        self.buttons = [] #we will add references to all buttons here

        for x in range(4):
            self.buttons.append(Button(text='button ' + str(x+1), size_hint=(0.5, 0.5), pos_hint={'x': .2, 'y': .4}))
            #make a reference to the button before adding it in
            self.add_widget(self.buttons[x])
            self.buttons[1].bind(on_press=self.on_click)


    def on_click(self, instance):
        print('clicked')

class SplashApp(App):
    def build(self):
        return LandingScreen()

if __name__ == '__main__':
    SplashApp().run()

2 个答案:

答案 0 :(得分:1)

您是说self.buttons[x].bind(on_press=self.click吗?

range(n)从0(含)到n(不含)。在第一个循环中,按钮列表中有一个项目,但是您正在访问第二个元素。

答案 1 :(得分:0)

删除该行的缩进,使其不成为循环的一部分:

class LandingScreen(BoxLayout):
    def __init__(self, **kwargs):
        super(LandingScreen, self).__init__(**kwargs)

        self.buttons = [] #we will add references to all buttons here

        for x in range(4):
            self.buttons.append(Button(text='button ' + str(x+1), size_hint=(0.5, 0.5), pos_hint={'x': .2, 'y': .4}))
            #make a reference to the button before adding it in
            self.add_widget(self.buttons[x])
        self.buttons[1].bind(on_press=self.on_click)


    def on_click(self, instance):
        print('clicked')