Search code examples
pythontkinterticker

Tkinter app not initiating after assigning label with variable using the .config method


I am trying to write a simple bitcoin ticker using the coinmarketcap module.

When I run the following code, the tkinter app does not load. No errors are given. I think I am calling everything properly but not sure what else could be at fault.

code:

from coinmarketcap import Market
import time
from tkinter import *
from tkinter import ttk
import tkinter as tk

def btc_ticker():
    while True:
        coinmarketcap = Market()
        btc_tick = coinmarketcap.ticker(1, convert ='GBP')
        btc_price = btc_tick['data']['quotes']['GBP']['price']
        #print(btc_price)
        time.sleep(2)
        btc_p.config(text = str(btc_price))
        root.after(2, btc_ticker)

root = Tk()
root.configure(background='black')

btc_p = Label(root, font=('consolas', 20, 'bold'), text="0",width =10, bg='black', fg='white')
btc_p.grid(row=0, column =0)

btc_ticker()

root.mainloop()

I can print the variable 'btc_price' so the assignment of this to btc_p through the .configure method should not be an issue.


Solution

  • Problem with your code was that you had while True loop before root.mainlop() which could't let it execute. Way to handle constant updates with tkinter is to use root.after(), which you implemented but not correctly. I removed while loop and left root.after at end of your function to let mainloop() execute. Also note that first argument of root.after is time in milliseconds, so to make your program wait 2 seconds that argument should be 2000.

    from coinmarketcap import Market
    from tkinter import *
    
    def btc_ticker():
        coinmarketcap = Market()
        btc_tick = coinmarketcap.ticker(1, convert ='GBP')
        btc_price = btc_tick['data']['quotes']['GBP']['price']
        #print(btc_price)
        btc_p.config(text = str(btc_price))
        root.after(2000, btc_ticker)
    
    root = Tk()
    root.configure(background='black')
    
    btc_p = Label(root, font=('consolas', 20, 'bold'), text="0",width =10, bg='black', fg='white')
    btc_p.grid(row=0, column =0)
    
    btc_ticker()
    root.mainloop()