from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 32)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=finpt.insert(0, f"{c_to_f(cvalue)}"))
to_f.pack()
window.mainloop()
After pressing the button, I want to return the show the result of c_to_f(cvalue) in Label c. How can I manage that?
CodePudding user response:
It is better to create another function for the button to_f
and do the conversion and show result inside that function:
from tkinter import *
def c_to_f(celsius):
return str(float(celsius) * 1.8 32)
def convert_to_fahrenheit():
try:
f = c_to_f(cinpt.get())
finpt.delete(0, END)
finpt.insert(END, f)
except ValueError as ex:
print(ex)
window = Tk()
f = Label(window, text="ºF")
f.pack()
finpt = Entry(window)
#fvalue = finpt.get()
finpt.pack()
c = Label(window, text="ºC")
c.pack()
cinpt = Entry(window)
#cvalue = cinpt.get()
cinpt.pack()
to_f = Button(window, text="Nach ºF umrechnen", command=convert_to_fahrenheit)
to_f.pack()
window.mainloop()
CodePudding user response:
Your code is giving too much problem.
Try this:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title('Temperature Converter')
root.geometry('300x70')
root.resizable(False, False)
def fahrenheit_to_celsius(f):
""" Convert fahrenheit to celsius
"""
return (f - 32) * 5/9
frame = ttk.Frame(root)
options = {'padx': 5, 'pady': 5}
temperature_label = ttk.Label(frame, text='Fahrenheit')
temperature_label.grid(column=0, row=0, sticky='W', **options)
temperature = tk.StringVar()
temperature_entry = ttk.Entry(frame, textvariable=temperature)
temperature_entry.grid(column=1, row=0, **options)
temperature_entry.focus()
def convert_button_clicked():
f = float(temperature.get())
c = fahrenheit_to_celsius(f)
result = f'{f} Fahrenheit = {c:.2f} Celsius'
result_label.config(text=result)
convert_button = ttk.Button(frame, text='Convert')
convert_button.grid(column=2, row=0, sticky='W', **options)
convert_button.configure(command=convert_button_clicked)
result_label = ttk.Label(frame)
result_label.grid(row=1, columnspan=3, **options)
frame.grid(padx=10, pady=10)
root.mainloop()
Screenshot: