Python Dark Night Sky Animation Using Tkinter

How to Create an Animated Dark Night Sky Using Canvas in Python and Tkinter

Python Dark Night Sky Animation Using Tkinter


In this Python tutorial we will create an animated dark night sky scene using canvas in the Tkinter library. 
The animation includes a static moon and moving stars.
DarkNightSky: A subclass of tk.Canvas that represents the night sky with stars. 
Moon: A separate class responsible for drawing the moon on the canvas.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:


import tkinter as tk
import random

class DarkNightSky(tk.Canvas):
# Constants for frame dimensions, number of stars, star size, and animation delay
frame_width = 800
frame_height = 600
num_stars = 100
star_size = 2
animation_delay = 50

def __init__(self, master=None, **kwargs):
super().__init__(master, width=self.frame_width, height=self.frame_height,
        bg="#262626", **kwargs)
self.stars = [] # List to store star coordinates
self.generate_stars() # Generate random star coordinates
self.moon = Moon(self) # Create Moon object
self.pack()

self.after(self.animation_delay, self.animate_stars) # Schedule the animation



def generate_stars(self):
# Generate random coordinates for stars and populate the stars list
for _ in range(self.num_stars):
x = random.randint(0, self.frame_width)
y = random.randint(0, self.frame_height)
self.stars.append((x,y))

def animate_stars(self):
self.move_stars() # Move stars for animation
        self.draw_scene() # Draw the entire scene
        # Schedule the next animation frame
self.after(self.animation_delay, self.animate_stars)

def draw_scene(self):
self.delete("all") # Clear the canvas
# Draw the dark night sky background
self.create_rectangle(0,0,self.frame_width, self.frame_height, fill="#262626")

# Draw each star on the canvas
for star in self.stars:
x, y = star
self.create_rectangle(x, y, x + self.star_size, y + self.star_size,
            fill="white", outline="white")

# Draw the moon on the canvas
self.moon.draw()
def move_stars(self):
# Move each star to the right and down,
        # reset if it goes beyond the frame boundaries
for i in range(len(self.stars)):
x , y = self.stars[i]
x += 1
y += 1
if x > self.frame_width:
x = 0
if y > self.frame_height:
y = 0
self.stars[i] = (x, y)



class Moon:
# Constants for moon radius and position
moon_radius = 150
moon_x = 550
moon_y = 100

def __init__(self, canvas):
self.canvas = canvas
def draw(self):
# Draw the moon on the canvas
self.canvas.create_oval(self.moon_x, self.moon_y,
        self.moon_x + self.moon_radius, self.moon_y + self.moon_radius,
        fill="#ffffff", outline="#f0f0f0")


if __name__ == "__main__":
root = tk.Tk()
root.title("Dark Night Sky")
app = DarkNightSky(root)
root.mainloop()


The Final Result:














Share this

Related Posts

Latest
Previous
Next Post »