2016-03-23 41 views
0

我想創建一個小窗口,告訴我前十名玩家資金。問題是,每次我點擊更新按鈕,它都不會刪除舊的播放器標籤列表。 tkinter中有明確的功能嗎?如何刷新tkinter和python中的標籤

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

回答

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

好主意....謝謝! – HELPMEPLEASE

1

而不是創建新Label的,你應該使用player.config(text="Some new value")方法。 (您將需要在全局變量中保留對標籤的引用)。

N.b.由於您有多個標籤,因此應該將對Label對象的引用保留在列表中。