2017-05-18 49 views
0

我讀過update_idletasks()中的許多帖子。我以爲我明白了,並且將其添加到代碼中。應該有#3的標籤顯示出來,因爲我只有3行記錄,但它沒有。爲什麼我的標籤不是自我更新?

我確實使用了一個按鈕,並且標籤起作用,但是update_idletask()沒有。

有沒有辦法不使用按鈕來通過使用update_idletasks()使這個標籤自我更新?

我在想它不工作,因爲它沒有進入循環? 請指導我。

import sqlite3 
import tkinter as t 
import time 

class SampleApp(t.Tk): 

    def __init__(self,parent): 
     t.Tk.__init__(self,parent) 
     self.parent=parent 
     self.initialize() 

    def initialize(self): 
     self.grid() 
#GUI------------------------------------- 
     self.labelVariable=t.StringVar() 
     self.label=t.Label(self, textvariable=self.labelVariable, bg="yellow", width=50, height=20) 
     self.label.pack(fill=t.X, expand=1) 


     #self.button=t.Button(self, text="get status", pady=5, command=self.status) 
     #self.button.pack(anchor=t.S, fill=t.X, expand=1) 


#formula______________________________________ 

    def status(self): 
     conn=sqlite3.connect("employees.db") 
     cursor=conn.cursor() 
     cursor.execute("SELECT COUNT(*) FROM Company") 
     self.labelVariable.set(cursor.fetchone()[0]) 

     self.update_idletasks() 
     self.after(0,self.status) 


app = SampleApp(None) 
app.mainloop() 

回答

0

你只需要調用self.status() ....和self.update_idletasks()是沒有必要的。如果你要打開連接,你也必須關閉它。

類改成這樣:

class SampleApp(t.Tk): 

    def __init__(self,parent): 
     t.Tk.__init__(self,parent) 
     self.parent=parent 
     self.initialize() 


    def initialize(self): 
     self.grid() 

     self.labelVariable=t.StringVar() 
     self.label=t.Label(self, textvariable=self.labelVariable, bg="yellow", width=50, height=20) 
     self.label.pack(fill=t.X, expand=1) 
     self.status() 

    def status(self): 
     conn=sqlite3.connect("employees.db") 
     cursor=conn.cursor() 
     cursor.execute("SELECT COUNT(*) FROM Company") 
     self.labelVariable.set(cursor.fetchone()[0]) 
     conn.close() 
     self.after(10,self.status) 

注意:你不應該爲delay參數.after 0或幾乎任何使用下10(單位爲毫秒)。

+0

我強烈建議不要'self.after(0,...)'。你應該使用更大的數字。使用零表示「之後」隊列從不清空,這可以防止正常事件被處理。即使是'1'(1)的值也會比零更好,儘管像'10'或'100'這樣的更大的數字會更好。 –

+0

你100%正確,我剛剛使用OP的示例 – abccd

+0

感謝您的快速回復,Bryan和abccd。我很感激。我更新了代碼,但仍然沒有看到我標籤上的號碼。 「3」行記錄。 – fishtang

相關問題