Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from kivy.clock import mainthread
- from kivymd.app import MDApp
- from kivymd.uix.screen import Screen
- from plyer import gps, notification
- import requests
- import json
- from datetime import datetime
- class WeatherScreen(Screen):
- api_key = "YOUR_API_KEY" # Get from openweathermap.org
- def on_enter(self):
- self.start_gps()
- def start_gps(self):
- try:
- gps.configure(on_location=self.on_location, on_status=self.on_status)
- gps.start(minTime=5000, minDistance=0)
- except NotImplementedError:
- notification.notify(title="GPS Error", message="GPS not supported")
- def on_status(self, stype, status):
- if status == 'provider-enabled':
- self.start_gps()
- def on_location(self, **kwargs):
- lat = kwargs.get('lat')
- lon = kwargs.get('lon')
- if lat and lon:
- self.get_weather(lat, lon)
- def get_weather(self, lat, lon):
- url = f"http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={self.api_key}&units=metric"
- try:
- response = requests.get(url)
- data = json.loads(response.text)
- self.update_ui(data)
- except Exception as e:
- notification.notify(title="Weather Error", message=str(e))
- @mainthread
- def update_ui(self, data):
- # Update main weather card
- self.ids.location_label.text = f"{data['name']}, {data['sys']['country']}"
- self.ids.temp_label.text = f"{round(data['main']['temp'])}°C"
- self.ids.update_label.text = f"Last update: {datetime.now().strftime('%H:%M:%S')}"
- # Update weather details
- self.ids.weather_icon.text = self.get_weather_icon(data['weather'][0]['id'])
- self.update_detail('💨', f"{data['wind']['speed']} m/s", "Wind")
- self.update_detail('💧', f"{data['main']['humidity']}%", "Humidity")
- self.update_detail('🌧️', f"{data.get('rain', {}).get('1h', 0)} mm", "Rain")
- def update_detail(self, icon, value, label):
- container = self.ids.details_card.children[0]
- for child in container.children:
- if child.label == label:
- child.ids.icon_label.text = icon
- child.ids.value_label.text = value
- break
- def get_weather_icon(self, code):
- if 200 <= code < 300: return "⛈️"
- if 300 <= code < 400: return "🌧️"
- if 500 <= code < 600: return "🌧️"
- if 600 <= code < 700: return "❄️"
- if 700 <= code < 800: return "🌫️"
- if code == 800: return "☀️"
- if 801 <= code < 900: return "⛅"
- return "🌍"
- def refresh(self):
- self.start_gps()
- self.ids.update_label.text = "Updating..."
- def on_leave(self):
- gps.stop()
- class WeatherApp(MDApp):
- def build(self):
- self.theme_cls.primary_palette = "Blue"
- return WeatherScreen()
- if __name__ == '__main__':
- WeatherApp().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement