索引器错误:元组索引超出范围---Python

2024-04-19 07:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮帮我。我正在运行一个简单的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)

这就是整个计划。。。。

错误是

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

有人能帮我吗???我是python新手。

非常感谢。。。。


Tags: textfromimporttopbuttonrootfillcursor
3条回答

元组由许多用逗号分隔的值组成。就像

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

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

在本例中,x = rows[1][1] + " " + rows[1][2]只有两个索引0,1可用,但您正试图访问第三个索引。

可能其中一个索引是错误的,要么是内部索引,要么是外部索引。

我想你是说[0]你说[1][1]你说[2]。在Python中,索引是基于0的。

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

相关问题 更多 >