Computer >> Máy Tính >  >> Lập trình >> Python

Máy tính tốc độ trung bình sử dụng Tkinter

Trong bài viết này, chúng ta sẽ xem cách tạo một ứng dụng dựa trên GUI sẽ tính toán tốc độ trung bình. Tốc độ trung bình của một đối tượng chuyển động có thể được tính bằng công thức sau,

Average Speed = Distance / [Hours + (Minutes/60)]

Để chọn giá trị đầu vào, chúng tôi sẽ sử dụng SpinBox phương pháp được sử dụng để tạo vòng xoay cho một phạm vi giá trị. Các giá trị này là Khoảng cách (Kilômét), Giờ và Phút.

Ví dụ

from tkinter import *
#Create an instance of tkinter frame
win = Tk()

#Set the geometry and resize the frame

win.geometry("700x400")
win.resizable(0,0)
win.title("Average Speed Calculator")
# Create Label for Main Window
Label(win, text="Average Speed Calculator",font=("Times New Roman", 18, "bold"), fg="black").pack()

# Calculate Average Speed
def average_cal():
#hrs
   hrs = int(hours.get())
#minutes
   mins = int(minutes.get())
#distance
   dist = int(distance.get())
#Formula
   Used avg = dist/(hrs+(mins/60))
#change the text of label using config method
   average_speed.config(text=f"{avg} Km/Hr")
# Create Mulitiple Frames
frame = Frame(win)
frame.pack()

frame1 = Frame(win)
frame1.pack()

frame2 = Frame(win)
frame2.pack()

# Create Labels and Spin Boxes
Label(frame, text="Hours", width=15, font=("Times New Roman", 12, "bold"),borderwidth=2, relief="solid").pack(side=LEFT, padx=10, pady=10) hours = Spinbox(frame, from_=0, to=1000000, width=5,font=("Times New Roman", 12, "bold")) hours.pack(side=LEFT, pady=10)

Label(frame1, text="Minutes", width=15, font=("Times New Roman", 12, "bold"),borderwidth=2, relief="solid").pack(side=LEFT, padx=10, pady=10) minutes = Spinbox(frame1, from_=0, to=10000000, width=5,font=("Times New Roman", 12, "bold")) minutes.pack(side=LEFT, pady=10)

Label(frame2, text="Distance in(Km)", width=15, font=("Times New Roman", 12, "bold"),borderwidth=2, relief="solid").pack(side=LEFT, padx=10, pady=10) distance = Spinbox(frame2, from_=0, to=1000000, width=5,font=("Times New Roman", 12, "bold")) distance.pack(side=LEFT, pady=10)

Button(win, text="Average Speed is:", width=15, font=("Times New Roman", 12, "bold"), command=average_cal, fg="white", bg="black").pack(pady=20)
average_speed = Label(win, text="", width=50, font=("Times New Roman", 12, "bold"), relief="solid") average_speed.pack()

# Execute
Tkinter win.mainloop()

Đầu ra

Chạy đoạn mã trên sẽ tạo và hiển thị Máy tính Trung bình.

Máy tính tốc độ trung bình sử dụng Tkinter