简体   繁体   中英

How do you refresh a label in tkinter and python

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

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

Nb Since you have more than one label, you should keep references to Label objects in a list.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM