按下按钮循环显示标签

时间:2018-01-29 05:26:04

标签: python python-3.x tkinter

所以我正在从数据库中读取内容,并将必要的元素添加到列表中。我试图在标签中显示列表中的每个元素。例如,我有一个数据库列表:

test = ['Name' , 'Age', 'Location']

我想在按下按钮时显示带有文字名称的标签(即test [0])。同样,当我再次按下按钮时,我想要显示标签,Age(即test [1])等等,直到列表的长度。我尝试了什么:

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

当我按下按钮时,显示最后一个元素,当我再次按下时,我得到列表索引超出范围。谁能告诉我我做错了什么?感谢

输出是列表中最后一个元素的标签,再次点击时出错:

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

1 个答案:

答案 0 :(得分:1)

for中的

func循环似乎没必要,因为您说要在每个印刷机上显示一个标签。去掉它。

如果你只是在课堂上使用它,你也可以在课堂内移动x

def __init__(self, master):
    ...
    self.x = 0

def func(self):
    self.display.config(text=str(all_ids[self.x]))
    self.nd.config(text=str(all_names[self.x]))
    self.x += 1