2016-11-14 128 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