2016-11-14 65 views
0

作爲第一個項目,我決定構建一個應用程序,它會顯示當前的石油價格,因此我不必一直查看外匯圖表。Constant Tkinter窗口更新

這個應用程序的問題是,「更新」循環只打印油價每3秒,所以我知道這個循環是不斷執行,但它不僅不更新窗口中的文本,但它也崩潰它,而殼打印油的價格。

我試過使用多處理模塊,但沒有區別。

def window(): 
    root = Tk() 
    screen_width = root.winfo_screenwidth() 
    screen_height = root.winfo_screenheight() 
    mylabel = Label(root, text = "") 
    mylabel.pack() 

def update(): 
    while True: 
     global string_price 
     request = requests.get("http://www.biznesradar.pl/notowania/BRENT-OIL-ROPA-BRENT#1d_lin_lin") 
     content = request.content 
     soup = BeautifulSoup(content, "html.parser") 
     element = soup.find("span", { "class": "q_ch_act" }) 
     string_price = (element.text.strip()) 
     print(string_price) 
     mylabel.configure(text = str(string_price)) 

     time.sleep(3) 

root.after(400, update) 
mainloop() 

回答

2

.after方法,已經做了你從while Truesleep希望在同一時間的東西。刪除sleepwhile並添加另一個after以連續呼叫。

def custom_update(): 
    global string_price 
    request = requests.get("http://www.biznesradar.pl/notowania/BRENT-OIL-ROPA-BRENT#1d_lin_lin") 
    content = request.content 
    soup = BeautifulSoup(content, "html.parser") 
    element = soup.find("span", {"class": "q_ch_act"}) 
    string_price = (element.text.strip()) 
    print(string_price) 
    mylabel.configure(text=str(string_price)) 
    root.after(3000, custom_update) #notice it calls itself after every 3 seconds 

custom_update() #since you want to check right after opening no need to call after here as Bryan commented 
+0

謝謝!它幫助了很多!我還在代碼最底部的「root.after」中更改了「0」的時間值,以便應用程序在開啓後立即檢查油價。 –

+0

你第一次打電話時不需要使用'after'。你可以直接調用'update()'。但是,您應該爲其他功能命名。所有的小部件都有'update'方法,所以擁有自己的'update'方法可能會讓人困惑。 –

+0

@KarolMularski請檢查後編輯以及。根據布賴恩的建議進行了一些更改。 – Lafexlos