繁体   English   中英

使用.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.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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM