Tkinter应用程序在使用.config方法为变量分配标签后未启动



我正在尝试使用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",因此通过.config方法将其分配给btc_p应该不会成为问题。

代码的问题是在root.mainlop()之前有while True循环,无法执行。使用tkinter处理持续更新的方法是使用root.after(),您实现了它,但没有正确实现。我删除了while循环,并在函数末尾留下root.after,让mainloop()执行。还要注意,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()

最新更新