Pytholic
Pytholic

Reputation: 25

Calling a function every n seconds in python

I'm trying to create a tk widget which auto-updates the score of a cricket match. this is my code. But it is not auto-updating. please help me with this.

import requests
from bs4 import BeautifulSoup

from tkinter import *
from tkinter import ttk
import time, threading 

def scrape_cric():
       #this below link can be any link of an ongoing match.
       page = 'http://www.cricbuzz.com/live-cricket-scores/18733/engu19-vs-bdeshu19-5th-place-playoff-semi-final-2-icc-under-19-world-cup-2018' 
       r = requests.get(page)
       soup = BeautifulSoup(r.text, 'lxml')
       score_1 = soup.find('div', {'class':'cb-min-bat-rw'})
       score = soup.find('span', {'class':'cb-font-20 text-bold'})
       return score.text


def display_Score():
       root = Tk()
       top_frame = Frame(root)
       bottom_frame = Frame(root)
       Label1 = Label(top_frame, text = scrape_cric())
       Label1.pack()
       top_frame.pack()
       mainloop()
       threading.Timer(10, display_Score()).start()


 display_Score()

It displays the score once on executing and doesn't auto-update. Once i close the tk widget, it again appears with updated scores. I don't want to close it to. It should update without e closing it.

Upvotes: 1

Views: 686

Answers (1)

Johny Vaknin
Johny Vaknin

Reputation: 287

The cause of this problem is beacuse you create a new root Tk in each call to the function instead of changing the text alone

A fix around that would be:

root = Tk()
top_frame = Frame(root)
label = Label(top_frame)
top_frame.pack()
label.pack()
def update():
    label['text']=scrape_cric()
    threading.Timer(10, update).start() #####
update()
root.mainloop()

Another important note: make sure you set the target of the timer to the function object, instead of calling it inside the creation of your timer

Upvotes: 1

Related Questions