Python 当索引在范围内时,如何修复索引超出范围

Python 当索引在范围内时,如何修复索引超出范围,python,kivy,kivy-language,Python,Kivy,Kivy Language,当我运行这个程序时,它会显示“self.buttons[1].bind(on_press=self.on_click)indexer错误:列表索引超出范围”,但我要访问的元素仍在范围内。我该如何解决这个问题 import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.button import Butto

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

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

你是说
self.buttons[x].bind(按=self.click


范围(n)
从0(包括)到n(排除)。在第一个循环中,按钮列表中有一项,但您正在访问第二个元素。

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

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

python中的列表从0索引。请尝试
self.buttons[0]。绑定(on\u press=self。on\u单击)
如果索引为0,它可以工作,但如果我将索引更改为1,2或3,它就不工作。我的意思是,如果我将索引更改为1,2或3,它就不工作,只有当索引为0时,它才会工作。目标是在创建按钮时将每个按钮绑定到函数,是吗?不,忘记绑定事件,我想更改第二个按钮的颜色,但我t不起作用,请再次查看代码。我建议的更改将允许您的代码运行。如果要更改第二个按钮的颜色,应在循环后添加:
self.buttons[1]。背景颜色=(0,0205,1)
非常感谢,它现在可以工作了。但请再说一件事,如果我想使用相同的索引更改按钮的位置,我将如何操作