使用 .config 方法分配带有变量的标签后,Tkinter 应用程序未启动

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

我正在尝试使用 coinmarketcap 模块编写一个简单的比特币自动收报机。

当我 运行 以下代码时,tkinter 应用程序不会加载。没有给出错误。我认为我正在正确调用所有内容,但不确定还有什么问题。

代码:

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

我可以打印变量 'btc_price',因此通过 .configure 方法将其分配给 btc_p 应该不是问题。

您的代码存在问题,因为您在 root.mainlop() 之前有 while True 循环,无法让它执行。使用 tkinter 处理持续更新的方法是使用 root.after(),您实现了但不正确。我删除了 while 循环并在函数末尾留下 root.aftermainloop() 执行。另请注意 root.after 的第一个参数是以毫秒为单位的时间,因此要让您的程序等待 2 秒,该参数应为 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()