IndexError:元组索引超出范围----- Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20296188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:07:17  来源:igfitidea点击:

IndexError: tuple index out of range ----- Python

pythonpython-2.7mysql-python

提问by Jerald Sanchez

Please Help me. I'm running a simple python program that will display the data from mySQL database in a tkinter form...

请帮我。我正在运行一个简单的 python 程序,它将以 tkinter 形式显示来自 mySQL 数据库的数据......

from Tkinter import *
import MySQLdb

def button_click():
    root.destroy()

root = Tk()
root.geometry("600x500+10+10")
root.title("Ariba")

myContainer = Frame(root)
myContainer.pack(side=TOP, expand=YES, fill=BOTH)

db = MySQLdb.connect ("localhost","root","","chocoholics")
s = "Select * from member"
cursor = db.cursor()
cursor.execute(s)
rows = cursor.fetchall()

x = rows[1][1] + " " + rows[1][2]
myLabel1 = Label(myContainer, text = x)
y = rows[2][1] + " " + rows[2][2]
myLabel2 = Label(myContainer, text = y)
btn = Button(myContainer, text = "Quit", command=button_click, height=1, width=6)

myLabel1.pack(side=TOP, expand=NO, fill=BOTH)
myLabel2.pack(side=TOP, expand=NO, fill=BOTH)
btn.pack(side=TOP, expand=YES, fill=NONE)

Thats the whole program....

这就是整个程序......

The error was

错误是

x = rows[1][1] + " " + rows[1][2]
IndexError: tuple index out of range

y = rows[2][1] + " " + rows[2][2]
IndexError: tuple index out of range

Can anyone help me??? im new in python.

谁能帮我???我是 Python 新手。

Thank you so much....

非常感谢....

采纳答案by glglgl

Probably one of the indexes is wrong, either the inner one or the outer one.

可能其中一个索引是错误的,无论是内部索引还是外部索引。

I suspect you mean to say [0]where you say [1]and [1]where you say [2]. Indexes are 0-based in Python.

我怀疑你的意思是说[0]你说的地方[1][1]你说的地方[2]。Python 中的索引是从 0 开始的。

回答by Ankit Singh

This is because your rowvariable/tuple does not contain any value for that index. You can try printing the whole list like print(row)and check how many indexes there exists.

这是因为您的变量/元组不包含该索引的任何值。您可以尝试打印整个列表,print(row)并检查存在多少个索引。

回答by Sai prateek

A tuple consists of a number of values separated by commas. like

元组由多个以逗号分隔的值组成。喜欢

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

元组在 Python 中是基于索引的(也是不可变的)。

Here in this case x = rows[1][1] + " " + rows[1][2]have only two index 0, 1 available but you are trying to access the 3rd index.

在这种情况下,这里x = rows[1][1] + " " + rows[1][2]只有两个索引 0, 1 可用,但您正在尝试访问第三个索引。