【问题标题】:How to Infinitely Update Labels with while loop tkinter如何使用 while 循环 tkinter 无限更新标签
【发布时间】:2018-01-28 06:42:18
【问题描述】:

您好,我这里有一些简单的代码。 https://pastebin.com/97uuqKQD

我只是想在按钮功能中添加类似这样的内容,因此当根窗口打开时,日期时间和费用会不断从 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 循环函数中,然后简单地调用该函数,但如果运气不好,将不胜感激。???

【问题讨论】:

    标签: python-3.x button tkinter label infinite-loop


    【解决方案1】:

    将其放在结果函数的末尾,不要使用 while 循环:

    after_id = root.after(milliseconds,results) 
    

    这样它只会在您指定的时间之后继续运行。此代码将取消它。

    root.after_cancel(after_id)
    


    在 cmets 中回答您的其他问题:
    要制作取消按钮,请确保 after_id 是全局的。此外,如果您指定的时间非常短(非常快的召回),它可能会在您取消之前再次重新启动。因此,为了安全起见,最好创建一个全局布尔值并将 .after 放入 if boolean==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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2021-01-04
      相关资源
      最近更新 更多