Seth Centerbar Seth Centerbar - 24 days ago 12
Python Question

String formatting using Python and Tkinter

I'm trying to get my first program with a gui created. The error I'm getting is as follows:

Exception in Tkinter callback

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/tkinter/__init__.py", line 1487, in __call__
return self.func(*args)
File "/Volumes/Mac Storage/Python /letsbuildagui.py", line 7, in calcppp
labelresult=Label(window,text="The average price per portion is: " % mappp).push()
TypeError: not all arguments converted during string formatting


The following is my code:

from tkinter import *

def calcppp():
lecost=float(cost.get())
leportions=float(portions.get())
mappp=lecost/leportions
labelresult=Label(window,text="The average price per portion is: " % mappp).push()
return

window = Tk()
window.geometry("500x500")
window.title("Price Per Portion")

cost=StringVar()
portions=StringVar()

welcome = Label(text='Please enter your total price of groceries \n and the amount of meals they yeilded to find out \n your average price per portion')
welcome.pack()
menubar = Menu(window)
button = Button(window, text="Calculate", command=calcppp)
button.place(x=200,y=450)
myCost=Entry(window,textvariable=cost).pack()
myPortions=Entry(window,textvariable=portions).pack()
window.config(menu=menubar)
window.mainloop()

Answer Source

You are using the string interpolation operator (%) but you aren't giving it anything to interpolate. You need to insert a format tag into the string.

change labelresult=Label(window,text="The average price per portion is: " % mappp).push()

this is giving you error

i think here it should be "The average price per portion is: %g " % mappp