如何使用while循环tkinter无限更新标签

问题描述:

嗨,我在这里有一些简单的代码。 https://pastebin.com/97uuqKQD如何使用while循环tkinter无限更新标签

我只是想添加类似这样的按钮功能,所以当根窗口打开时,日期时间和扩展时间会不断从xe网站恢复并显示出来。

amount = '1' 

def continuousUpdate(): 
    while amount == '0': 
     results() 

def results(): 
    #Get xe data put to labels etc here 

btnConvert = tk.Button(root, text="Get Exchange Rates",command=continuousUpdate).place(x=5,y=102) 

一旦我输入两个exrates,然后他们显示那里各自的标签,我想程序不断从xe中一遍又一遍地获取数据。

像这里这样的代码,在IPython中运行没有问题,

import requests 
from bs4 import BeautifulSoup 
from datetime import datetime 

amount = '1' 

while amount != '0': 
    t = datetime.utcnow() 
    url1 = "http://www.xe.com/currencyconverter/convert/" + "?Amount=" + amount + "&From=" + cur1 + "&To=" + cur2 
    url2 = "http://www.xe.com/currencyconverter/convert/" + "?Amount=" + amount + "&From=" + cur2 + "&To=" + cur1 
    #url = "http://www.xe.com/currencycharts/" + "?from=" + cur1 + "&to=" + cur2    
    html_code1 = requests.get(url1).text 
    html_code2 = requests.get(url2).text 

    soup1 = BeautifulSoup(html_code1, 'html.parser') 
    soup2 = BeautifulSoup(html_code2, 'html.parser') 

    i = i + 1 

    rate1 = soup1.find('span', {'class', 'uccResultAmount'}) 
    rate2 = soup2.find('span', {'class', 'uccResultAmount'}) 

    print ('#',i, t,'\n', cur1,'-',cur2, rate1.contents[0], cur2,'-',cur1, rate2.contents[0], '\n') 

我想我也只是能够引发整个结果函数成while循环功能,然后简单地调用该函数,但没有运气任何帮助将不胜感激。

将这个在你的结果函数结束时没有while循环:

after_id = root.after(milliseconds,results) 

这样,它只是让你指定的时间后运行本身。这段代码将取消它。

root.after_cancel(after_id) 


回答您的其他问题的意见:
要取消按钮确保after_id是全球性的。此外,如果您指定的时间很短(非常快速调用),它可能会重新启动,然后才能取消它。所以为了安全起见,建立一个全局布尔值并将其放入一个if布尔值== True中。你可以设置布尔为False,只要你打取消按钮或为True,只要你打的启动按钮,这里是你如何能做到这一点:

# button_call default will be True so if you click on the button 
# this will be True (no need to pass var through). You can use this to set 
# your restart boolean to True 
def func(button_call=True): 
    global restart 
    global after_id 
    if button_call: 
     restart = True 
    if restart: 
     after_id = root.after(ms,lambda: func(button_call=False)) 
     # This way you know that func was called by after and not the button 

现在你可以把这个在您的取消按钮功能:

def cancel(): 
    global restart 
    global after_id 
    root.after_cancel(after_id) 
    restart = False 

让我知道这是否有效(自己还没有测试过)。