File size: 1,176 Bytes
4be9855 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import gradio as gr
def calculate_mpg(miles, fuel):
"""
Core logic function to calculate MPG.
This replaces the logic inside the Tkinter class.
"""
try:
# Input validation
if fuel <= 0:
return "Error: Fuel must be > 0"
if miles < 0:
return "Error: Miles cannot be negative"
# Calculation
mpg = miles / fuel
return f"{round(mpg, 2)} MPG"
except Exception as e:
return f"Error: {str(e)}"
# Define the Gradio Interface
# 1. Inputs: Two number boxes
# 2. Output: A text box for the result
# 3. Title/Description: For the top of the web page
interface = gr.Interface(
fn=calculate_mpg,
inputs=[
gr.Number(label="Miles Driven", value=0),
gr.Number(label="Fuel Consumption (Gallons)", value=0)
],
outputs=gr.Textbox(label="Calculated Fuel Economy"),
title="FUEL ECONOMY CALCULATOR",
description="Enter miles and fuel to calculate your MPG. This is a web-based version of our Tkinter assignment.",
theme="soft" # Optional: gives it a modern look
)
# Launch the app
if __name__ == "__main__":
interface.launch()
|