Reputation: 402
I am creating a calculator using drop-down menus in my code. I have two drop-down options and some entries.
root = tk.Tk()
plans = {
'Maintain': '0',
'Fat Loss': '-500',
'Muscle Gain': '350'
}
levels = {
'Low': '12',
'Low Medium': '13',
'Medium': '14',
'Medium High': '15',
'High': '16'
}
plan = tk.Label(root, text='Choose a plan:', justify=tk.RIGHT)
plan.grid(column=1, columnspan=2, row=5)
plan_var = tk.StringVar(root)
plan_var.set('Maintain')
plan_dropdown = tk.OptionMenu(root, plan_var, *plans)
plan_dropdown.grid(column=4, row=5)
agg = tk.Label(root, text='Choose a level: ', justify=tk.RIGHT)
agg.grid(column=1, columnspan=2, row=7)
maint_var = tk.StringVar(root)
maint_var.set('Low')
maint_dropdown = tk.OptionMenu(root, maint_var, *levels)
maint_dropdown.grid(column=4, row=7)
So I want to write a function that would calculate plan_var
selection (so either -500
or 350
) added to maint_var
selection (from 12
to 16
, included)".
def calculate():
calories_total = int(plan_var.get()) + int(maint_var.get())*int(bw_entry.get())
print(calories_total)
submit = tk.Button(root, text='Calculate', command=calculate)
submit.grid(column=4, row=9)
root.mainloop()
I know my calculate function is wrong and missing something, just not sure how to write it out.
Upvotes: 1
Views: 189
Reputation: 5372
First, make your dictionaries a dictionary of integers so you don't need to do conversions when calculating and also assign a value of 0
to plans['Maintain']
:
plans = {
'Maintain': 0,
'Fat Loss': -500,
'Muscle Gain': 350
}
levels = {
'Low': 12,
'Low Medium': 13,
'Medium': 14,
'Medium High': 15,
'High': 16
}
After that, to do the calculation you want, you need to access the value of the corresponding dictionary key pointed by plan_var
and maint_var
. Something like this:
def calculate():
print(plans[plan_var.get()] + levels[maint_var.get()])
The example above just print the sum on the console. If you want to do something else, just return
that value and deal with it in your code.
Gluing it all together:
import tkinter as tk
def calculate():
print(plans[plan_var.get()] + levels[maint_var.get()])
plans = {
'Maintain': 0,
'Fat Loss': -500,
'Muscle Gain': 350
}
levels = {
'Low': 12,
'Low Medium': 13,
'Medium': 14,
'Medium High': 15,
'High': 16
}
root = tk.Tk()
plan = tk.Label(root, text='Choose a plan: ', justify=tk.RIGHT)
plan.grid(column=1, columnspan=2, row=5)
plan_var = tk.StringVar(root)
plan_var.set('Maintain')
plan_dropdown = tk.OptionMenu(root, plan_var, *plans)
plan_dropdown.grid(column=4, row=5)
agg = tk.Label(root, text='Choose a level: ', justify=tk.RIGHT)
agg.grid(column=1, columnspan=2, row=7)
maint_var = tk.StringVar(root)
maint_var.set('Low')
maint_dropdown = tk.OptionMenu(root, maint_var, *levels)
maint_dropdown.grid(column=4, row=7)
submit = tk.Button(root, text='Calculate', command=calculate)
submit.grid(column=4, row=9)
root.mainloop()
Upvotes: 1