Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create a GUI to Get Sunset and Sunrise Time using Python
In this tutorial, we'll create a GUI application using Python's Tkinter library to display sunrise and sunset times for any location. We'll use the astral library to calculate astronomical data based on geographic coordinates.
Prerequisites
Before starting, ensure you have:
Python 3.x installed ? Tkinter comes bundled with Python
Astral library ? Install using:
pip install astralBasic Python knowledge ? Functions, classes, and GUI concepts
Installing Required Libraries
The astral library provides astronomical calculations for sunrise, sunset, and twilight times
pip install astral
Importing Required Modules
import tkinter as tk from tkinter import ttk, messagebox from astral.sun import sun from astral import LocationInfo from datetime import datetime import pytz
Creating the Complete GUI Application
Here's the complete application that allows users to select a city and get sunrise/sunset times
import tkinter as tk
from tkinter import ttk
from astral.sun import sun
from astral import LocationInfo
from datetime import datetime
class SunriseSunsetApp:
def __init__(self, root):
self.root = root
self.root.title("Sunrise & Sunset Time Calculator")
self.root.geometry("400x300")
self.root.configure(bg='#f0f0f0')
self.create_widgets()
def create_widgets(self):
# Title Label
title_label = tk.Label(
self.root,
text="? Sunrise & Sunset Calculator ?",
font=("Arial", 16, "bold"),
bg='#f0f0f0',
fg='#2c3e50'
)
title_label.pack(pady=20)
# City Selection Frame
city_frame = tk.Frame(self.root, bg='#f0f0f0')
city_frame.pack(pady=10)
tk.Label(city_frame, text="Select City:", font=("Arial", 12), bg='#f0f0f0').pack(side=tk.LEFT)
self.city_var = tk.StringVar()
cities = ["New York", "London", "Tokyo", "Sydney", "Mumbai", "Cairo"]
self.city_combo = ttk.Combobox(city_frame, textvariable=self.city_var, values=cities, state="readonly")
self.city_combo.set("New York")
self.city_combo.pack(side=tk.LEFT, padx=10)
# Get Time Button
get_time_btn = tk.Button(
self.root,
text="Get Sunrise & Sunset Times",
command=self.get_times,
font=("Arial", 12),
bg='#3498db',
fg='white',
relief='raised',
padx=20,
pady=5
)
get_time_btn.pack(pady=20)
# Results Frame
self.results_frame = tk.Frame(self.root, bg='#ecf0f1', relief='sunken', bd=2)
self.results_frame.pack(pady=10, padx=20, fill='both', expand=True)
self.result_label = tk.Label(
self.results_frame,
text="Click the button to get times",
font=("Arial", 11),
bg='#ecf0f1',
justify='left'
)
self.result_label.pack(pady=20)
def get_city_info(self, city_name):
# City coordinates and timezone mapping
city_data = {
"New York": ("New York", "USA", "America/New_York", 40.7128, -74.0060),
"London": ("London", "UK", "Europe/London", 51.5074, -0.1278),
"Tokyo": ("Tokyo", "Japan", "Asia/Tokyo", 35.6762, 139.6503),
"Sydney": ("Sydney", "Australia", "Australia/Sydney", -33.8688, 151.2093),
"Mumbai": ("Mumbai", "India", "Asia/Kolkata", 19.0760, 72.8777),
"Cairo": ("Cairo", "Egypt", "Africa/Cairo", 30.0444, 31.2357)
}
return city_data.get(city_name)
def get_times(self):
try:
selected_city = self.city_var.get()
if not selected_city:
self.result_label.config(text="Please select a city!")
return
city_data = self.get_city_info(selected_city)
if not city_data:
self.result_label.config(text="City not found!")
return
city_name, country, timezone, latitude, longitude = city_data
# Create LocationInfo object
city = LocationInfo(city_name, country, timezone, latitude, longitude)
# Calculate sun times for today
s = sun(city.observer, date=datetime.now(), tzinfo=city.timezone)
sunrise = s['sunrise'].strftime('%H:%M:%S')
sunset = s['sunset'].strftime('%H:%M:%S')
# Display results
result_text = f"""? Location: {city_name}, {country}
? Date: {datetime.now().strftime('%Y-%m-%d')}
? Sunrise: {sunrise}
? Sunset: {sunset}
? Timezone: {timezone}"""
self.result_label.config(text=result_text)
except Exception as e:
self.result_label.config(text=f"Error: {str(e)}")
# Create and run the application
if __name__ == "__main__":
root = tk.Tk()
app = SunriseSunsetApp(root)
root.mainloop()
Key Features
City Selection ? Dropdown menu with predefined cities
Real-time Calculation ? Uses current date for accurate times
Timezone Support ? Displays times in local timezone
Error Handling ? Manages exceptions gracefully
User-friendly Interface ? Clean and intuitive design
How the Code Works
LocationInfo Class ? Creates a location object with coordinates and timezone
sun() Function ? Calculates sunrise/sunset times for the given location and date
Timezone Handling ? Ensures times are displayed in the correct local timezone
GUI Components ? Uses Tkinter widgets for user interaction and display
Customization Options
You can extend this application by
Adding more cities ? Expand the city_data dictionary
Manual coordinates ? Allow users to input latitude/longitude
Date selection ? Add calendar widget for different dates
Additional solar events ? Include dawn, dusk, and twilight times
Conclusion
This tutorial demonstrates creating a practical GUI application that combines astronomical calculations with user interface design. The astral library provides accurate solar time calculations, while Tkinter creates an intuitive interface for users to interact with the data.
