I have been working on the Tkinter module for a few weeks now and started writing a GUI. I have a problem when I press the calculate button it doesn't show anything. The goal for it is to show the conversion of 25 meters into feet when the user selects meters or when the user selects feet to convert to meters. I want it to work like in this video right here. Any help would be appreciated. https://youtu.be/1z41yet2DkI
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Length Converter")
def calculate(*args):
# Conversion of meters
if choices == "meters":
value = float(meters.get())
feet.set(int(3.281 * value * 10000.0 + 0.5)/10000.0)
# Conversion of feet
if choices == "feet":
value = float(feet.get())
meters.set(int(0.3048 * value * 10000.0 + 0.5) / 10000.0)
mainframe = ttk.Frame(root, padding= "25 25 25 25")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
meters = StringVar()
feet = StringVar()
n = StringVar()
input_entry = ttk.Entry(mainframe, width=7, textvariable=meters)
input_entry.grid(column=2, row=1, sticky=(W, E))
choices = ttk.Combobox (root, width = 10, textvariable = n)
choices ['values'] = ('meters', 'feet')
choices.grid(column = 1, row = 1)
ttk.Label(mainframe, text="is equal to").grid(column=1, row=2, sticky=E)
ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=2, row=3, sticky=W)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
root.mainloop()
The following does basically what you want. I renamed your StringVar
s and added an additional one to hold the result.
rom tkinter import *
from tkinter import ttk
def calculate(*args):
if choices.get() == 'meters':
value = float(inp.get())
result.set(int(3.281 * value * 10000.0 + 0.5) / 10000.0)
units.set('feet')
if choices.get() == 'feet':
value = float(inp.get())
result.set(int(0.3048 * value * 10000.0 + 0.5) / 10000.0)
units.set('meters')
root = Tk()
root.title('Length Converter')
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
mainframe = ttk.Frame(root, padding='25 25 25 25')
mainframe.grid(sticky=(N, W, E, S))
inp = StringVar()
choice = StringVar()
result = StringVar()
units = StringVar()
input_entry = ttk.Entry(mainframe, width=7, textvariable=inp)
input_entry.grid(row=1, column=0)
choices = ttk.Combobox(mainframe, width=10, textvariable=choice, values=('meters', 'feet'))
choices.grid(row=1, column=1)
ttk.Label(mainframe, text='is equal to').grid(row=2, column=0)
ttk.Label(mainframe, textvariable=result).grid(row=2, column=1, sticky=E)
ttk.Label(mainframe, textvariable=units).grid(row=2, column=2, sticky=W)
ttk.Button(mainframe, text='Calculate', command=calculate).grid(row=3, column=1)
for child in mainframe.winfo_children():
child.grid_configure(padx=5, pady=5)
root.mainloop()