Karol Mularski Karol Mularski - 24 days ago 7
Python Question

Constant Tkinter window update

As a first project I decided to build an app that will show me the current price of oil so I will not have to look at the Forex charts whole time.

The issue with this app is that the "update" loop only prints oil price every 3 seconds, so I know that this loop is executed constantly, but it not only does not update the text in window, but it also crashes it, while shell prints the price of oil.

I tried to use Multiprocessing module but it made no diffrence.

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()

Answer

.after method, already does what you wanted from while True and sleep at the same time. Remove both sleep and while and add another after inside to call continuously.

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