So I'm reading contents from the database and I have appended necessary elements into lists. I am trying to display each elements in the list in a label. For example, I have a list from the database:
test = ['Name' , 'Age', 'Location']
I want to display the label with text- Name (i.e test[0]) on button press. Likewise, when I press the button again I want the label to display, Age (i.e. test[1]) and so on upto the length of the list. What I tried:
from tkinter import *
import sqlite3
# connecting to the database
conn = sqlite3.connect('database.db')
c = conn.cursor()
# empty lists to later append elements into
all_ids = []
all_names = []
all_time = []
# execute sql
sql = ('SELECT * FROM appointments')
res = c.execute(sql)
for r in res:
idd = r[0]
name = r[1]
time = r[6]
all_ids.append(idd)
all_names.append(name)
all_time.append(time)
# variable that determines the index of elements on button press (updates)
x = 0
class Application:
def __init__(self, master):
self.master = master
self.heading = Label(master, text="Appointments", font=('arial 60 bold'), fg='steelblue')
self.heading.place(x=300, y=0)
self.btn = Button(master, text="Next Patient", width=20, height=2, command=self.func)
self.btn.place(x=500, y=600)
self.display = Label(self.master, text="", font=('arial 200 bold'))
self.display.place(x=500, y=80)
self.nd = Label(self.master, text="", font=('arial 80 bold'))
self.nd.place(x=200, y=400)
def func(self):
global x
for i in all_ids:
self.display.config(text=str(all_ids[x]))
self.nd.config(text=str(all_names[x]))
x += 1
root = Tk()
v = Application(root)
root.geometry("1366x768+0+0")
root.resizable(False, False)
root.mainloop()
When I press the button, last element is displayed and when I press again, I get list index out of range. Can anyone please tell me what I'm doing wrong? Thanks
Output is the label of last element in the list and error on clicking again:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
return self.func(*args)
File "test.py", line 45, in func
self.display.config(text=str(all_ids[x]))
IndexError: list index out of range