Python.无法将列表项放入单个变量中.当我这样做时,变量包含整个列表项


def nextPage():
conn = sqlite3.connect('xyz.db')
c = conn.cursor()

c.execute("INSERT INTO persons VALUES (?,?)",(text.get(),text1.get()))

conn.commit()
conn.close()
def submit():     
conn = sqlite3.connect('xyz.db')
c =conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS persons(
name1 TEXT,
name2 TEXT)''')        
conn.commit()
conn.close()

def query():
conn = sqlite3.connect('xyz.db')
c = conn.cursor()
c.execute('SELECT * FROM persons')
records = c.fetchall()
print(records[0])
conn.commit()
conn.close()

import sqlite3
from tkinter import *
from tkinter import ttk
import tkinter as tk
ws = Tk()
ws.geometry('770x400')
ws.title('PythonGuides')
a = Label(ws ,text = "Name").grid(row = 1,column = 0)
b = Label(ws ,text = "Name of Spouse or CP, if applicable").grid(row = 2,column = 0)
text = Entry(ws)
text.grid(row = 1 , column = 1)
text1 = Entry(ws)
text1.grid(row = 2 , column = 1)
btn = ttk.Button(ws ,text="Submit", command = submit).grid(row=4,column=0)
Button(
ws, 
text="Next Page", command=nextPage).grid(row = 5,column = 10)
query()
ws.mainloop
#OUTPUT
#('JOHN', '')

我正在使用Tkinter和sqlite进行一个项目。即使是你,我也只想打印列表中的第一项,整个列表都被输出了。我想把项目放在单独的变量中,但每次,整个列表都存储在一个变量中。如有任何帮助,我们将不胜感激。

我想问题出在records = c.fetchall()行。fetchall()返回元组列表,其中每个元组是数据库中的一行。因此,当您使用print(records[0])时,您正在打印整个第一个元组。

要进行故障排除,请尝试print(records),打印整个列表records,然后查看该列表的外观。然后,您可以调整print函数的索引,只打印您想要打印的内容。

records = c.fetchall()
print(records[0])

存储在records中的值是tuples中的list,因此records[0]tuple

在Python中,tuple是可迭代的,因此它们是索引的,并且是可访问的,类似于列表:

print(records[0][0])

最新更新