Rabu, 22 April 2026

Python - Animation Wheels WIth Text 3

 




import tkinter as tk

import math


# --- Configuration ---

WIDTH, HEIGHT = 800, 300

RECT_W, RECT_H = 150, 60

WHEEL_RADIUS = 25

SPOKE_COLOR = "white"

ROTATION_SPEED = 15


class Vehicle:

    def __init__(self, canvas, x, y):

        self.canvas = canvas

        self.x = x

        self.y = y

        self.angle = 0

        self.speed = 0

        

        # Create components

        self.body = self.canvas.create_rectangle(

            x, y, x + RECT_W, y + RECT_H, fill="brown", outline="black", width=2)

        self.text = self.canvas.create_text(

            x + RECT_W/2, y + RECT_H/2, text="Hello", fill="white", font=('Arial', 16, 'bold'))

        

        # Wheels

        self.wheel1 = self.create_wheel(x + 30, y + RECT_H)

        self.wheel2 = self.create_wheel(x + RECT_W - 30, y + RECT_H)

        self.wheels = [self.wheel1, self.wheel2]


    def create_wheel(self, cx, cy):

        # Circle

        circle = self.canvas.create_oval(

            cx - WHEEL_RADIUS, cy - WHEEL_RADIUS,

            cx + WHEEL_RADIUS, cy + WHEEL_RADIUS, fill="black")

        

        # 4 Spokes

        spokes = []

        for i in range(4):

            spokes.append(self.canvas.create_line(cx, cy, cx, cy, fill=SPOKE_COLOR, width=2))

        return {'circle': circle, 'spokes': spokes, 'center': (cx, cy)}


    def move(self, direction):

        # Update position

        self.speed = direction * 10

        self.angle += direction * ROTATION_SPEED

        self.canvas.move(self.body, self.speed, 0)

        self.canvas.move(self.text, self.speed, 0)

        

        for wheel in self.wheels:

            self.canvas.move(wheel['circle'], self.speed, 0)

            

            # Rotate Spokes

            cx, cy = wheel['center'][0] + self.speed, wheel['center'][1] # This is wrong, needs to track total move

        

        # Properly move and rotate everything

        self.update_components()


    def update_components(self):

        # Update centers based on total movement

        self.x += self.speed

        

        # Move wheels and re-calculate spokes

        for wheel in self.wheels:

            # Re-center spokes based on current wheel position

            cx = self.canvas.coords(wheel['circle'])[0] + WHEEL_RADIUS

            cy = self.canvas.coords(wheel['circle'])[1] + WHEEL_RADIUS

            wheel['center'] = (cx, cy)

            

            for i in range(4):

                angle = math.radians(self.angle + (i * 90))

                x2 = cx + WHEEL_RADIUS * math.cos(angle)

                y2 = cy + WHEEL_RADIUS * math.sin(angle)

                self.canvas.coords(wheel['spokes'][i], cx, cy, x2, y2)


# --- Setup ---

root = tk.Tk()

root.title("Moving Vehicle")

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg="white")

canvas.pack()


vehicle = Vehicle(canvas, 50, 150)


# --- Controls ---

def left(event): vehicle.move(-1)

def right(event): vehicle.move(1)


root.bind("<Left>", left)

root.bind("<Right>", right)


root.mainloop()



Python - Animation Wheels WIth Text 2

 




import tkinter as tk

import math


# Configuration

WIDTH, HEIGHT = 800, 300

WHEEL_RADIUS = 30

SPOKE_LEN = WHEEL_RADIUS - 2

RECT_WIDTH, RECT_HEIGHT = 150, 60

SPEED = 5

ANGLE_STEP = 0.2


# Initialize Tkinter

root = tk.Tk()

root.title("Animated Wagon")

canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT, bg='white')

canvas.pack()


# Initial Positions

rect_x = 50

rect_y = HEIGHT - 100

angle = 0


def draw_spokes(x, y, angle):

    """Draws 4 rotating spokes for a wheel."""

    spokes = []

    for i in range(4):

        a = angle + (i * math.pi / 2)

        x1 = x + SPOKE_LEN * math.cos(a)

        y1 = y + SPOKE_LEN * math.sin(a)

        x2 = x - SPOKE_LEN * math.cos(a)

        y2 = y - SPOKE_LEN * math.sin(a)

        spokes.append(canvas.create_line(x1, y1, x2, y2, fill="white", width=2))

    return spokes


def animate():

    global rect_x, angle

    

    # Update positions

    rect_x += SPEED

    angle += ANGLE_STEP

    

    # Wrap around screen

    if rect_x > WIDTH:

        rect_x = -RECT_WIDTH

        

    # Clear and Redraw Everything

    canvas.delete("all")

    

    # Draw Brown Rectangle

    canvas.create_rectangle(rect_x, rect_y, rect_x + RECT_WIDTH, rect_y + RECT_HEIGHT, fill="#8B4513", outline="")

    canvas.create_text(rect_x + RECT_WIDTH/2, rect_y + RECT_HEIGHT/2, text="hello", fill="white", font=('Arial', 16))

    

    # Wheel Centers

    wh1_x, wh2_x = rect_x + 30, rect_x + RECT_WIDTH - 30

    wh_y = rect_y + RECT_HEIGHT + 10

    

    # Draw Wheels (circles)

    for cx in [wh1_x, wh2_x]:

        canvas.create_oval(cx-WHEEL_RADIUS, wh_y-WHEEL_RADIUS, cx+WHEEL_RADIUS, wh_y+WHEEL_RADIUS, fill="black", outline="white")

        draw_spokes(cx, wh_y, angle)

        

    root.after(30, animate)


# Start animation

animate()

root.mainloop()

Python - Animation Wheels WIth Text 1

 



import tkinter as tk

import math


# --- Configuration ---

WINDOW_WIDTH = 800

WINDOW_HEIGHT = 400

WHEEL_RADIUS = 30

SPOKES = 4

SPEED = 3  # pixels per frame

ROTATION_SPEED = 5  # degrees per frame


class MovingCar:

    def __init__(self, canvas):

        self.canvas = canvas

        self.angle = 0

        self.x = 50

        self.y = 250


        # Create wheels

        self.left_wheel = self.canvas.create_oval(

            self.x, self.y,

            self.x + WHEEL_RADIUS * 2, self.y + WHEEL_RADIUS * 2,

            outline="black", width=2

        )

        self.right_wheel = self.canvas.create_oval(

            self.x + 120, self.y,

            self.x + 120 + WHEEL_RADIUS * 2, self.y + WHEEL_RADIUS * 2,

            outline="black", width=2

        )


        # Create spokes for each wheel

        self.left_spokes = []

        self.right_spokes = []

        for _ in range(SPOKES):

            self.left_spokes.append(self.canvas.create_line(0, 0, 0, 0, fill="black", width=2))

            self.right_spokes.append(self.canvas.create_line(0, 0, 0, 0, fill="black", width=2))


        # Create rectangle body

        self.body = self.canvas.create_rectangle(

            self.x - 10, self.y - 50,

            self.x + 160, self.y,

            fill="brown"

        )


        # Create text

        self.text = self.canvas.create_text(

            self.x + 75, self.y - 25,

            text="hello", fill="white", font=("Arial", 14, "bold")

        )


    def update_spokes(self, wheel_center_x, wheel_center_y, spokes_list):

        """Update spoke positions based on current rotation angle."""

        for i, spoke in enumerate(spokes_list):

            angle_deg = self.angle + (360 / SPOKES) * i

            rad = math.radians(angle_deg)

            x_end = wheel_center_x + WHEEL_RADIUS * math.cos(rad)

            y_end = wheel_center_y + WHEEL_RADIUS * math.sin(rad)

            self.canvas.coords(spoke, wheel_center_x, wheel_center_y, x_end, y_end)


    def move(self):

        # Move all parts to the right

        self.canvas.move(self.left_wheel, SPEED, 0)

        self.canvas.move(self.right_wheel, SPEED, 0)

        self.canvas.move(self.body, SPEED, 0)

        self.canvas.move(self.text, SPEED, 0)

        for spoke in self.left_spokes + self.right_spokes:

            self.canvas.move(spoke, SPEED, 0)


        # Update rotation

        self.angle = (self.angle + ROTATION_SPEED) % 360


        # Get wheel centers

        lx1, ly1, lx2, ly2 = self.canvas.coords(self.left_wheel)

        rx1, ry1, rx2, ry2 = self.canvas.coords(self.right_wheel)

        left_center = ((lx1 + lx2) / 2, (ly1 + ly2) / 2)

        right_center = ((rx1 + rx2) / 2, (ry1 + ry2) / 2)


        # Update spokes

        self.update_spokes(*left_center, self.left_spokes)

        self.update_spokes(*right_center, self.right_spokes)


        # Loop animation

        if lx1 < WINDOW_WIDTH:

            self.canvas.after(30, self.move)


# --- Main Program ---

root = tk.Tk()

root.title("Rotating Wheels Animation")


canvas = tk.Canvas(root, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg="skyblue")

canvas.pack()


car = MovingCar(canvas)

car.move()


root.mainloop()

Python - Animation Wheels WIth Text And Missile

 



import tkinter as tk

import math


# --- Configuration ---

W, H = 800, 400

WHEEL_RADIUS = 30

SPOKES = 4

VEHICLE_SPEED = 3

ROTATION_SPEED = 5  # degrees per frame

MISSILE_SPEED = 8


class VehicleAnimation:

    def __init__(self, root):

        self.root = root

        self.canvas = tk.Canvas(root, width=W, height=H, bg="skyblue")

        self.canvas.pack()


        # Initial position

        self.x = 100

        self.y = 250

        self.angle = 0

        self.missiles = []


        # Draw wheels

        self.left_wheel = self.canvas.create_oval(

            self.x, self.y, self.x + WHEEL_RADIUS*2, self.y + WHEEL_RADIUS*2, fill="black"

        )

        self.right_wheel = self.canvas.create_oval(

            self.x + 120, self.y, self.x + 120 + WHEEL_RADIUS*2, self.y + WHEEL_RADIUS*2, fill="black"

        )


        # Draw spokes

        self.left_spokes = []

        self.right_spokes = []

        for _ in range(SPOKES):

            self.left_spokes.append(self.canvas.create_line(0, 0, 0, 0, fill="white", width=2))

            self.right_spokes.append(self.canvas.create_line(0, 0, 0, 0, fill="white", width=2))


        # Draw vehicle body

        self.body = self.canvas.create_rectangle(

            self.x + 10, self.y - 40, self.x + 170, self.y, fill="saddlebrown"

        )


        # Add text

        self.text = self.canvas.create_text(

            self.x + 90, self.y - 20, text="hello", font=("Arial", 14), fill="white"

        )


        # Draw cannon

        self.cannon = self.canvas.create_rectangle(

            self.x + 150, self.y - 50, self.x + 170, self.y - 40, fill="gray"

        )


        # Bind space key for firing

        self.root.bind("<space>", self.fire_missile)


        # Start animation

        self.animate()


    def draw_spokes(self, wheel_center_x, wheel_center_y, spokes_list):

        """Draw rotating spokes for a wheel."""

        for i in range(SPOKES):

            angle_deg = self.angle + (360 / SPOKES) * i

            angle_rad = math.radians(angle_deg)

            x1 = wheel_center_x + math.cos(angle_rad) * WHEEL_RADIUS

            y1 = wheel_center_y + math.sin(angle_rad) * WHEEL_RADIUS

            x2 = wheel_center_x - math.cos(angle_rad) * WHEEL_RADIUS

            y2 = wheel_center_y - math.sin(angle_rad) * WHEEL_RADIUS

            self.canvas.coords(spokes_list[i], x1, y1, x2, y2)


    def fire_missile(self, event=None):

        """Create a missile from the cannon."""

        missile = self.canvas.create_rectangle(

            self.x + 170, self.y - 45, self.x + 180, self.y - 40, fill="red"

        )

        self.missiles.append(missile)


    def animate(self):

        # Move vehicle

        self.x += VEHICLE_SPEED

        self.angle = (self.angle + ROTATION_SPEED) % 360


        # Update wheel positions

        self.canvas.coords(self.left_wheel,

                           self.x, self.y,

                           self.x + WHEEL_RADIUS*2, self.y + WHEEL_RADIUS*2)

        self.canvas.coords(self.right_wheel,

                           self.x + 120, self.y,

                           self.x + 120 + WHEEL_RADIUS*2, self.y + WHEEL_RADIUS*2)


        # Update spokes

        self.draw_spokes(self.x + WHEEL_RADIUS, self.y + WHEEL_RADIUS, self.left_spokes)

        self.draw_spokes(self.x + 120 + WHEEL_RADIUS, self.y + WHEEL_RADIUS, self.right_spokes)


        # Update body, text, cannon

        self.canvas.coords(self.body,

                           self.x + 10, self.y - 40,

                           self.x + 170, self.y)

        self.canvas.coords(self.text,

                           self.x + 90, self.y - 20)

        self.canvas.coords(self.cannon,

                           self.x + 150, self.y - 50,

                           self.x + 170, self.y - 40)


        # Move missiles

        for missile in list(self.missiles):

            self.canvas.move(missile, MISSILE_SPEED, 0)

            coords = self.canvas.coords(missile)

            if coords[0] > W:  # Remove if off-screen

                self.canvas.delete(missile)

                self.missiles.remove(missile)


        # Loop animation

        self.root.after(30, self.animate)



if __name__ == "__main__":

    root = tk.Tk()

    root.title("Vehicle Animation with Cannon")

    app = VehicleAnimation(root)

    root.mainloop()



Sabtu, 18 April 2026

Python XML 4

 



import tkinter as tk
from tkinter import ttk
import xml.etree.ElementTree as ET

# 1. Sample XML Data (could be loaded from a file)
xml_data = """<?xml version="1.0"?>
<library>
    <book id="1">
        <title>Python Basics</title>
        <author>John Doe</author>
        <year>2020</year>
    </book>
    <book id="2">
        <title>Tkinter Guide</title>
        <author>Jane Smith</author>
        <year>2022</year>
    </book>
</library>
"""

def load_xml_data(tree):
    # Parse XML
    root = ET.fromstring(xml_data)
    
    # Iterate over XML elements and insert into treeview
    for book in root.findall('book'):
        book_id = book.get('id')
        title = book.find('title').text
        author = book.find('author').text
        year = book.find('year').text
        tree.insert("", "end", values=(book_id, title, author, year))

# Create GUI
root = tk.Tk()
root.title("XML to Treeview")

# 2. Setup Treeview
columns = ("id", "title", "author", "year")
tree = ttk.Treeview(root, columns=columns, show="headings")

# Define Headings
tree.heading("id", text="ID")
tree.heading("title", text="Title")
tree.heading("author", text="Author")
tree.heading("year", text="Year")

# Define Columns
tree.column("id", width=50)
tree.column("title", width=200)
tree.column("author", width=150)
tree.column("year", width=50)

tree.pack(pady=20)

# Load data
load_xml_data(tree)

root.mainloop()


Python XML 3




import tkinter as tk

from tkinter import ttk, messagebox, filedialog

import xml.etree.ElementTree as ET

import os


def load_xml_data(file_path):

    """Load and parse XML file, returning headers and rows."""

    try:

        tree = ET.parse(file_path)

        root = tree.getroot()


        # Assume each child of root is a row, and its sub-elements are columns

        rows = []

        headers = set()


        for row_elem in root:

            row_data = {}

            for col_elem in row_elem:

                headers.add(col_elem.tag)

                row_data[col_elem.tag] = col_elem.text or ""

            rows.append(row_data)


        headers = sorted(headers)  # Keep consistent order

        return headers, rows


    except ET.ParseError:

        messagebox.showerror("XML Error", "Invalid XML format.")

        return [], []

    except FileNotFoundError:

        messagebox.showerror("File Error", "File not found.")

        return [], []

    except Exception as e:

        messagebox.showerror("Error", str(e))

        return [], []


def display_table(headers, rows):

    """Display data in a Tkinter Treeview table."""

    # Clear old table if exists

    for widget in table_frame.winfo_children():

        widget.destroy()


    if not headers or not rows:

        tk.Label(table_frame, text="No data to display").pack()

        return


    # Create Treeview

    tree = ttk.Treeview(table_frame, columns=headers, show="headings")

    tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)


    # Add column headings

    for header in headers:

        tree.heading(header, text=header)

        tree.column(header, width=120, anchor="center")


    # Insert rows

    for row in rows:

        tree.insert("", tk.END, values=[row.get(h, "") for h in headers])


    # Add scrollbar

    scrollbar = ttk.Scrollbar(table_frame, orient="vertical", command=tree.yview)

    tree.configure(yscroll=scrollbar.set)

    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)


def open_file():

    """Open file dialog and load XML data."""

    file_path = filedialog.askopenfilename(

        title="Select XML File",

        filetypes=[("XML Files", "*.xml"), ("All Files", "*.*")]

    )

    if file_path:

        headers, rows = load_xml_data(file_path)

        display_table(headers, rows)


# --- Tkinter GUI Setup ---

root = tk.Tk()

root.title("XML Data Table Viewer")

root.geometry("700x400")


# Menu

menu_bar = tk.Menu(root)

file_menu = tk.Menu(menu_bar, tearoff=0)

file_menu.add_command(label="Open XML", command=open_file)

file_menu.add_separator()

file_menu.add_command(label="Exit", command=root.quit)

menu_bar.add_cascade(label="File", menu=file_menu)

root.config(menu=menu_bar)


# Table Frame

table_frame = tk.Frame(root)

table_frame.pack(fill=tk.BOTH, expand=True)


# Start GUI

root.mainloop()

 



Python XML 2

 




import tkinter as tk
from tkinter import ttk
import xml.etree.ElementTree as ET

# Fungsi untuk memuat dan mencari data dari XML
def search_data():
    query = search_entry.get().lower()
    
    # Hapus data lama di tabel sebelum menampilkan hasil baru
    for row in tree.get_children():
        tree.delete(row)
        
    try:
        # Load file XML (Ganti 'data.xml' dengan nama file Anda)
        tree_xml = ET.parse('data2.xml')
        root = tree_xml.getroot()
        
        for item in root.findall('item'):
            # Ambil data dari tag XML (sesuaikan nama tag dengan file Anda)
            name = item.find('name').text
            category = item.find('category').text
            price = item.find('price').text
            
            # Filter berdasarkan input pencarian
            if query in name.lower() or query in category.lower():
                tree.insert("", "end", values=(name, category, price))
                
    except FileNotFoundError:
        print("Error: File 'data.xml' tidak ditemukan.")

# --- Setup GUI ---
root = tk.Tk()
root.title("Pencarian Data XML")
root.geometry("600x400")

# 1. Kotak Input Pencarian
search_frame = tk.Frame(root)
search_frame.pack(pady=10)

tk.Label(search_frame, text="Cari:").pack(side=tk.LEFT, padx=5)
search_entry = tk.Entry(search_frame, width=30)
search_entry.pack(side=tk.LEFT, padx=5)

# Tombol Search
search_btn = tk.Button(search_frame, text="Cari", command=search_data)
search_btn.pack(side=tk.LEFT)

# 2. Tabel Data (Treeview)
columns = ("Name", "Category", "Price")
tree = ttk.Treeview(root, columns=columns, show="headings")

# Definisi Header Tabel
for col in columns:
    tree.heading(col, text=col)
    tree.column(col, width=150)

tree.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# Jalankan fungsi pencarian pertama kali untuk memuat semua data
search_data()

root.mainloop()
==============================
data2.xml
<?xml version="1.0"?>
<root>
    <item>
        <name>Laptop</name>
        <category>Electronics</category>
        <price>1200</price>
    </item>
    <item>
        <name>Mouse</name>
        <category>Electronics</category>
        <price>100</price>
    </item>
    <item>
        <name>Speaker</name>
        <category>Electronics</category>
        <price>120</price>
    </item>
     <item>
        <name>Flasdisk</name>
        <category>Electronics</category>
        <price>10</price>
    </item>
    <item>
        <name>Keyboard</name>
        <category>Electronics</category>
        <price>120</price>
    </item>

</root>