【问题标题】:Display labels using loop on button press按下按钮时使用循环显示标签
【发布时间】:2018-01-29 05:26:03
【问题描述】:

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

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

我想在按下按钮时显示带有文本名称的标签(即 test[0])。同样,当我再次按下按钮时,我希望显示标签、年龄(即 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

【问题讨论】:

  • 你能在那里追溯你的错误吗?
  • 更新了问题
  • 您可以在fun () 内部尝试而不是在外部初始化x,例如x=0 并删除global x
  • 我试过了,它只返回最后一个元素。我需要的是每次单击按钮时更新标签
  • 在当前的代码中,我认为您没有在哪里使用i。所以你可以把那个循环改成for i in range(len(all_ids)): all_ids[i],而不是那些你可以使用的地方xi

标签: python python-3.x tkinter


【解决方案1】:

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

如果你只在课堂上使用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

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多