Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

python - time.sleep function isnt working in kivy app

I have here a simple app that displays the current bitcoin price:

import kivy
from kivy.app import App
from kivy.uix.label import Label 
import requests 
import time 


class MyApp(App):
    def build(self):
        while True:
            
            url = requests.get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").json()
            price = url['bitcoin']['usd']
            return Label(text="Bitcoin Price
 " + str(price) + " USD", font_size=72)
            time.sleep(10)


if __name__ == '__main__':
    MyApp().run()

When i run this app it works, however according to the coingecko api, they update the price every 120 seconds but the price in my app never updates.

I tried to set the time to 120 seconds 10 seconds 30 seconds etc but my price doesnt update after running. And i dont get any error when running the problem so i dont know what the issue is


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using time.sleep() is not advisable for GUI programs as it will make the GUI unresponsive. Instead use the Clock.schedule_interval() provided by kivy

Here is the corrected code

import kivy
import kivy
from kivy.app import App
from kivy.uix.label import Label 
import requests 
from kivy.clock import Clock
 

class MyApp(App):

    def update_price(self, lbl):
        url = requests.get("https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd").json()
        price = url['bitcoin']['usd']

        lbl.text = "Bitcoin Price
 " + str(price) + " USD"

    def build(self):
            
        lbl = Label(font_size=72)
        # self.update_price(lbl)
        Clock.schedule_interval(lambda _:self.update_price(lbl), 1) # updates every 1 second

        return lbl

if __name__ == '__main__':
    MyApp().run()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...