정보통신기술(ICT)

파이썬 소프트웨어: 거리와 속도와 시간

해머슴 2024. 11. 23. 20:56
import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def calculate():
    try:
        distance = float(distance_entry.get()) if distance_entry.get() else None
        speed = float(speed_entry.get()) if speed_entry.get() else None
        time = float(time_entry.get()) if time_entry.get() else None

        if distance and speed:
            time = distance / speed
            time_entry.delete(0, tk.END)
            time_entry.insert(0, f"{time:.2f}")
        elif distance and time:
            speed = distance / time
            speed_entry.delete(0, tk.END)
            speed_entry.insert(0, f"{speed:.2f}")
        elif speed and time:
            distance = speed * time
            distance_entry.delete(0, tk.END)
            distance_entry.insert(0, f"{distance:.2f}")
        else:
            result_label.config(text="Fill at least two fields!")
            return

        plot_graph(distance, speed, time)
        result_label.config(text="Calculation complete!")
    except ValueError:
        result_label.config(text="Please enter valid numbers!")

def plot_graph(distance, speed, time):
    fig.clear()
    ax = fig.add_subplot(111)
    labels = ['Distance (km)', 'Speed (km/h)', 'Time (h)']
    values = [distance, speed, time]

    ax.bar(labels, values)
    ax.set_title("Distance-Speed-Time Graph")
    ax.set_ylabel("Values")
    canvas.draw()

# Create the main window
root = tk.Tk()
root.title("Distance-Speed-Time Calculator")

# Input fields
frame = ttk.Frame(root)
frame.pack(pady=10, padx=10)

distance_label = ttk.Label(frame, text="Distance (km):")
distance_label.grid(row=0, column=0, padx=5, pady=5)
distance_entry = ttk.Entry(frame)
distance_entry.grid(row=0, column=1, padx=5, pady=5)

speed_label = ttk.Label(frame, text="Speed (km/h):")
speed_label.grid(row=1, column=0, padx=5, pady=5)
speed_entry = ttk.Entry(frame)
speed_entry.grid(row=1, column=1, padx=5, pady=5)

time_label = ttk.Label(frame, text="Time (h):")
time_label.grid(row=2, column=0, padx=5, pady=5)
time_entry = ttk.Entry(frame)
time_entry.grid(row=2, column=1, padx=5, pady=5)

calculate_button = ttk.Button(frame, text="Calculate", command=calculate)
calculate_button.grid(row=3, column=0, columnspan=2, pady=10)

result_label = ttk.Label(frame, text="")
result_label.grid(row=4, column=0, columnspan=2, pady=5)

# Graph area
fig = plt.Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(pady=10)

root.mainloop()