使用Python和Tkinter进行字符串格式化

时间:2014-07-02 07:02:57

标签: python tkinter

我试图用gui创建我的第一个程序。我得到的错误如下:

Tkinter回调中的异常

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

以下是我的代码:

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()

2 个答案:

答案 0 :(得分:3)

您的代码中存在多个错误

1)您可以使用label.config()选项动态更新标签,例如:

myLabel.config(text="The average price per portion is: %d" %mappp)

2)Label实例没有属性'push'。

3)行:

menubar = Menu(window)

window.config(menu=menubar)

没用,因为程序中没有菜单

4)为什么您使用place()几何管理器作为按钮,而pack()使用其他人。 place()通常用于绝对布局,最好避免使用。由于您使用pack来处理所有其他小部件,因此最好使用pack,即使是按钮也是如此。

以下是针对所有这些错误修改的代码:

from tkinter import *

def calcppp():
    lecost=float(cost.get())
    leportions=float(portions.get())
    mappp=lecost/leportions
    myLabel.config(text="The average price per portion is: %d" %mappp)
    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()
myCost=Entry(window,textvariable=cost)
myCost.pack()
myPortions=Entry(window,textvariable=portions)
myPortions.pack() 
button = Button(window, text="Calculate", command=calcppp)
button.pack()
myLabel = Label(window)
myLabel.pack()

答案 1 :(得分:2)

您正在使用字符串插值运算符(%),但您没有给它任何内插。您需要在字符串中插入格式标记。

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

这会给你错误

我认为这应该是"The average price per portion is: %g " % mappp