from tkinter import *
def apenas_numeros(texto):
if texto == "":
return True
# Permite números e um único ponto ou vírgula decimal
texto_val = texto.replace(",", ".")
if texto_val.count(".") <= 1:
partes = texto_val.split(".")
if all(parte.isdigit() for parte in partes if parte):
return True
return False
def limpar():
preço_total_entrada.delete(0, END)
Peso_grama_entrada.delete(0, END)
resultado_texto.config(text="", bg="#cfe2f3")
preço_total_entrada.focus()
def app():
try:
# Substitui vírgula por ponto para conversão correta em float
total = float(preço_total.get().replace(",", "."))
grama = float(Peso_grama.get().replace(",", "."))
if total <= 0 or grama <= 0:
mensagem = "As variáveis têm de ser maiores que 0."
else:
preço_kg = (total / grama) * 1000
mensagem = f"Preço por quilo = {round(preço_kg, 2):.2f} €/kg"
# Atualiza a etiqueta de resultado com sucesso
resultado_texto.config(
text=mensagem,
bg="#cfe2f3",
fg="#103030"
)
except ValueError:
resultado_texto.config(
text="Por favor, insira apenas números válidos.",
bg="#cfe2f3",
fg="red"
)
root = Tk()
root.geometry("700x400")
root.resizable(0, 0)
root.config(bg="#103030")
root.title("Calcular o preço por quilo")
vcmd = root.register(apenas_numeros) # Validação de números
# Título
titulo = Label(
root,
text="Calcular o preço por quilo",
font=("Arial", 28, "bold"),
bg="#103030",
fg="#49e3e3"
)
titulo.place(relx=0.15, rely=0.05)
# Labels
Label(
root,
text="Preço Total (€):",
font=("Arial", 18, "bold"),
bg="#103030",
fg="#49e3e3"
).place(relx=0.2, rely=0.25)
Label(
root,
text="Peso em grama(g):",
font=("Arial", 18, "bold"),
bg="#103030",
fg="#49e3e3"
).place(relx=0.15, rely=0.43)
preço_total = StringVar()
preço_total_entrada = Entry(
root,
textvariable=preço_total,
font=("Arial", 12, "bold"),
justify='center',
validate="key",
validatecommand=(vcmd, "%P")
)
preço_total_entrada.place(relx=0.6, rely=0.26, relwidth=0.35)
preço_total_entrada.focus()
Peso_grama = StringVar()
Peso_grama_entrada = Entry(
root,
textvariable=Peso_grama,
font=("Arial", 12, "bold"),
justify='center',
validate="key",
validatecommand=(vcmd, "%P")
)
Peso_grama_entrada.place(relx=0.6, rely=0.43, relwidth=0.35)
root.bind("<Return>", lambda event: app())
Button(
root, text="Calcular", bg='#107db2', fg='white',
font=('Verdana', 12, 'bold'), command=app
).place(relx=0.1, rely=0.65, relwidth=0.25, relheight=0.1)
Button(
root, text="Limpar", bg='#107db2', fg='white',
font=('Verdana', 12, 'bold'), command=limpar
).place(relx=0.4, rely=0.65, relwidth=0.25, relheight=0.1)
Button(
root, text="Sair", bg='#107db2', fg='white',
font=('Verdana', 12, 'bold'), command=root.destroy
).place(relx=0.7, rely=0.65, relwidth=0.25, relheight=0.1)
resultado_texto = Label(
root, text="", font=("Arial", 14, "bold"), bg="#cfe2f3", fg="#103030"
)
resultado_texto.place(relx=0.05, rely=0.8, relwidth=0.9, relheight=0.15)
root.mainloop()