Reputation: 51
I am trying to create a small windows that tell me the top ten players bankrolls. The problem is that everytime I hit the update button it doesnt delete the old list of player labels. Is there a clear functions in 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()
Upvotes: 0
Views: 1271
Reputation: 2691
Instead of creating a new Label
, you should use the player.config(text="Some new value")
method. (You will need to keep a reference to the Label in a global variable).
N.b. Since you have more than one label, you should keep references to Label objects in a list.
Upvotes: 1
Reputation: 8855
Since the getlist()
is creating a new Label
for each item, one approach would be to remove previous list from the window (and memory), and generate a new list of players (and labels).
We need to keep a reference to created labels (in getlist()
) so later we can remove them. Something like this code (trying to change as minimum of the code sample in question):
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()
Upvotes: 1