I'm currently working a bit with the code below, but everytime I try to hit the calcButt, button, it doesn't really do anything. What seems to be the problem - what am I doing wrong? I've only started coding python a month ago so I've very new to this. I hope you guys can help me :)
from tkinter import *
import Calculations
root = Tk()
# ***** function - is in an imported document *****
def calc_kJ(Protein, Carbs, Fat):
protein = Protein * 17
carbs = Carbs * 17
fat = Fat * 37
return protein + carbs + fat
# ***** Labels and inputs *****
proteinLabel = Label(root, text="Protein in gram:")
carbsLabel = Label(root, text="Carbs in gram:")
fatLabel = Label(root, text="Fat in gram:")
proteinInput = Entry(root)
carbsInput = Entry(root)
fatInput = Entry(root)
calcButt = Button(text="Calculate amount of kJ", command=Calculations.calc_kJ(Protein=proteinInput.get(), Carbs=carbsInput.get(), Fat=fatInput.get()))
# ***** Grid layout *****
proteinLabel.grid(row=0, sticky=W)
carbsLabel.grid(row=1, sticky=W)
fatLabel.grid(row=2, sticky=W)
proteinInput.grid(row=0,column=1)
carbsInput.grid(row=1, column=1)
fatInput.grid(row=2, column=1)
calcButt.grid(row=3, columnspan=2)
root.mainloop()
What are you expecting to happen? Where does the value returned by calc_kJ
need to go?
The way you wrote your code, the command of the button is the value returned by calc_kJ
instead of a call to the function.
You're going to want a function that passes the values from the Entry boxes to the calc_kJ
function and does the appropriate thing with the returned value. Something like:
def calc():
kJ = calc_kJ(Protein=int(proteinInput.get()), Carbs=int(carbsInput.get()), Fat=int(fatInput.get()))
calcButt.config(text=str(kJ)+" kJ")
As you can see, this function first gets the values from the entry, converted into integers, and passes them to calc_kJ
to do the calculation. Then, the returned value is put as the text of the button. To use this function you have to configure your button with command=calc
.