我正在尝试创建一个小窗口,告诉我前十名玩家的资金。问题是,每当我点击更新按钮时,它都不会删除旧的播放器标签列表。 tkinter中有明确的功能吗?
CODE:
from tkinter import *
import sqlite3
def getlist():
conn = sqlite3.connect('C:\sqlite\crapsdatabase.db')
c = conn.cursor()
c.execute("SELECT playerName, playerBank FROM player ORDER BY playerBank desc limit 10")
temp = c.fetchall()
for row in temp:
texthold = str(row[0]) + ' ' + str(row[1])
print(texthold)
player = Label(root, text=texthold)
player.pack()
conn.commit() #confirms changes to the databae
c.close() #closes the connection to the database
conn.close()
root =Tk()
theLabel =Label(root, text="Top Ten Players")
buttonUpdate = Button(root, text="Update", fg="green", command = getlist)
buttonUpdate.pack()
theLabel.pack()
root.mainloop()
答案 0 :(得分:1)
您应该使用Label
方法,而不是创建新的player.config(text="Some new value")
。 (您需要在全局变量中保留对Label的引用。)
N.b。由于您有多个标签,因此应该在列表中保留对Label对象的引用。
答案 1 :(得分:1)
由于getlist()
正在为每个项目创建新的Label
,因此一种方法是从窗口(和内存)中删除以前的列表,并生成一个新的播放器列表(和标签)
我们需要保留对已创建标签的引用(在getlist()
中),以便稍后我们可以删除它们。像这样的代码(试图改变代码样本的最小值):
from tkinter import *
import sqlite3
top_list = [] # holds the player labels currently shown
def getlist():
global top_list
conn = sqlite3.connect('C:\sqlite\crapsdatabase.db')
c = conn.cursor()
c.execute("SELECT playerName, playerBank FROM player ORDER BY playerBank desc limit 10")
temp = c.fetchall()
for player in top_list:
player.pack_forget() # remove label from window
top_list = [] # remove references to free memory
for row in temp:
texthold = str(row[0]) + ' ' + str(row[1])
print(texthold)
player = Label(root, text=texthold)
player.pack()
top_list.append(player)
conn.commit() #confirms changes to the databae
c.close() #closes the connection to the database
conn.close()
root = Tk()
theLabel = Label(root, text="Top Ten Players")
buttonUpdate = Button(root, text="Update", fg="green", command=getlist)
buttonUpdate.pack()
theLabel.pack()
root.mainloop()