Search code examples
python-3.xtkinterlabelurllibupdating

TKinter auto updating label from urllib


I'm trying make auto updating label from url. I want to make something like pager. When file on server is changed, label should changes too. with button I can download it manually but I want to automate it. Where I'm making mistake?

from tkinter import *
import urllib.request
import time

root = Tk()
check = ""

#functions
def auto():
    time.sleep(5)  #becouse I don't want kill server
    page = "http://howan.pl/pychal/plik.txt"
    g = urllib.request.urlopen(page)
    data = g.read()
    g.close()
    return (str(data, encoding='utf-8'))

def click():
    page = "http://howan.pl/pychal/plik.txt"
    g = urllib.request.urlopen(page)
    data = g.read()
    g.close()
    label.config(text=str(data, encoding='utf-8'))

#Widgets
label = Label(root, text="zer0")
button = Button(root, text="hey", command= click)

if auto() == check:
    check = auto
    label.config(text=check)
    print(auto())

label.pack()
button.pack()
root.mainloop()

Solution

  • To automate it you need to make a function that does the work, and then use root.after() to call that function on a regular basis. Since you have all the work in "click" already, you could just add:

    def auto_click():
        click()
        root.after(5000, auto_click) # call this function again in 5,000 ms (5 seconds)
    
    auto_click() # start the autoclick loop.