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:














Java - Create Gradient Buttons

How to Create Buttons with Gradient Backgrounds In Java Netbeans

Gradient Buttons In Java


In this Java Tutorial we will see How To Create custom jbutton with a gradient background that transitions from one color to another in Java using NetBeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package new_tutorials;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author 1BestCsharp
 */
public class GradientButton extends JButton{

    private Color startColor;
    private Color endColor;
    
    public GradientButton(String text, Color startColor, Color endColor){
        
        super(text);
        this.startColor = startColor;
        this.endColor = endColor;
        setContentAreaFilled(false);
        setFocusPainted(false);
        setForeground(Color.WHITE);
        setPreferredSize(new Dimension(150, 70));  
        setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    
    
    @Override
    protected void paintComponent(Graphics g){
        
        Graphics2D g2d = (Graphics2D)g.create();
        // Create a gradient paint
        GradientPaint gradientPaint = new GradientPaint(
                new Point2D.Float(0,0), startColor,
                new Point2D.Float(0,getHeight()), endColor
        );
        
        g2d.setPaint(gradientPaint);
        // Fill the button background with the gradient
        g2d.fillRect(0, 0, getWidth(), getHeight());
        
        super.paintComponent(g);
        
        g2d.dispose();
        
    }
    
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Gradient Button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        
        GradientButton button = new GradientButton("Button", Color.GREEN, Color.BLUE);
        
        frame.add(button);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
    }
    
}


The Final Result:

Buttons with Gradient Backgrounds In Java 1

Buttons with Gradient Backgrounds In Java 2

Buttons with Gradient Backgrounds In Java 3

Buttons with Gradient Backgrounds In Java 4

Buttons with Gradient Backgrounds In Java 5

Buttons with Gradient Backgrounds In Java 6






Using Python And Tkinter to Open, Read, and Save Text Files

How to Open, Read, and Save Text Files Using Python and Tkinter

How to Open, Read, and Save Text Files Using Tkinter in Python


In this Python tutorial we will create an application that allows users to open, read, and save text files using the Tkinter library for the graphical user interface. 
The application features a text editor and a menu bar for file operations, including open, save, and exit options.

What We Are Gonna Use In This Project:

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




Project Source Code:



import tkinter as tk
from tkinter import ttk, filedialog

class TextFile_OpenReadSave:
def __init__(self, master):

# Initialize the main application
self.master = master
master.title("Open Read Save Text File")

# Styling
master.geometry("600x400")
master.configure(bg="#f0f0f0")

# Create a Text widget for text editing
self.text_editor = tk.Text(master)
self.text_editor.pack(expand=True, fill=tk.BOTH)

# Create a menu bar
self.menubar = tk.Menu(master)

# Create a File menu in the menu bar
self.file_menu = tk.Menu(self.menubar, tearoff=0)

# Add commands to the File menu
self.file_menu.add_command(label="Open", command = self.open_file)
self.file_menu.add_command(label="Save", command = self.save_file)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command = master.quit)

# Add the File menu to the menu bar
self.menubar.add_cascade(label="File", menu=self.file_menu)

# Configure the menu bar for the main window
master.config(menu=self.menubar)

def open_file(self):
# Ask user to select a file for opening
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"),
        ("All Files", "*.*")])

if file_path:
# Read the contents of the selected file and insert it into the text editor
with open(file_path, "r") as file:
self.text_editor.delete("1.0", tk.END)
self.text_editor.insert(tk.END, file.read())


def save_file(self):
# Ask user to select a file for saving
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
        filetypes=[("Text Files", "*.txt"),("All Files", "*.*")])

if file_path:
# Write the contents of the text editor to the selected file
with open(file_path, "w") as file:
file.write(self.text_editor.get("1.0", tk.END))




if __name__ == "__main__":
root = tk.Tk()
app = TextFile_OpenReadSave(root)
root.mainloop()


The Final Result:

Using Tkinter in Python to Open, Read, and Save Text Files









Java Colors Generator

How to Create a Color Codes Generator In Java Netbeans

How to Create a Color Codes Generator In Java Netbeans




In this Java Tutorial we will see How To Make a simple color generator application with a graphical interface using Java Swing In Netbeans.
The application allows users to generate random colors and displays the color labels along with their corresponding HEX values. 

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.






Project Source Code:





package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author 1BestCsharp
 */
public class Color_Generator_App extends JFrame{
    
    private JLabel[] colorLabels;
    private JTextField[] colorTextFields;
    private JButton generateColorsButton;
    
    public Color_Generator_App(){
        // Set the window title and properties
        setTitle("Color Generator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocationRelativeTo(null);
        // Initialize the user interface
        intializeGUI();
    }
    
    private void intializeGUI(){
        // Create arrays to store color labels, text fields, and the generate button
        colorLabels = new JLabel[3];
        colorTextFields = new JTextField[3];
        generateColorsButton = new JButton("Generate Colors");
        
        // Create the main panel to hold components
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridLayout(3,2,10,10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        
        // Create and add color labels and text fields to the main panel
        for(int i = 0; i < 3; i++)
        {
            colorLabels[i] = new JLabel("Color " + (i+1));
            colorLabels[i].setOpaque(true);
            colorLabels[i].setBackground(Color.white);
            colorLabels[i].setBorder(BorderFactory.createLineBorder(Color.black,1));
            colorLabels[i].setHorizontalAlignment(JLabel.CENTER);
            
            colorTextFields[i] = new JTextField();
            colorTextFields[i].setEditable(false);
            colorTextFields[i].setBackground(Color.white);
            colorTextFields[i].setBorder(BorderFactory.createLineBorder(Color.black,1));
            colorTextFields[i].setHorizontalAlignment(JTextField.CENTER);
            
            mainPanel.add(colorLabels[i]);
            mainPanel.add(colorTextFields[i]);
            
        }
        
        // Add the main panel to the center of the JFrame
        add(mainPanel, BorderLayout.CENTER);
        
        // Define the action when the "Generate Colors" button is clicked
        generateColorsButton.addActionListener(((e) -> {
            // Generate random colors and update labels and text fields
            for(int i = 0; i < 3; i++)
            {
              Color randomColor = generateRandomColor();  
              String colorCode = "#" + Integer.toHexString(randomColor.getRGB()).substring(2).toUpperCase();
              colorLabels[i].setBackground(randomColor);
              colorTextFields[i].setText(colorCode);
            }
            
        }));
        
        // Configure the "Generate Colors" button
        generateColorsButton.setPreferredSize(new Dimension(150,40));
        generateColorsButton.setFont(new Font("Arial", Font.PLAIN, 14));
        generateColorsButton.setBackground(new Color(30,144,255));
        generateColorsButton.setForeground(Color.WHITE);
        generateColorsButton.setFocusPainted(false);
        generateColorsButton.setBorderPainted(false);
        
        // Create a panel for the button and add it to the bottom of the JFrame
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(generateColorsButton);
        add(buttonPanel,BorderLayout.SOUTH);
        
    }
    
    
    // Method to generate a random color
    private Color generateRandomColor()
    {
        int red = (int) (Math.random()*256);
        int green = (int) (Math.random()*256);
        int blue = (int) (Math.random()*256);
        
        return new Color(red,green,blue);
    }
    

    public static void main(String[] args) {
        new Color_Generator_App().setVisible(true);
    }
    
}


The Final Result:

Java Color Generator

Generate Random Colors Using Java

Random colors generator in java

Color Codes Generator In Java

Java Color Generator