2014-07-02 39 views
2

我試圖用gui創建我的第一個程序。我得到的錯誤如下:使用Python和Tkinter進行字符串格式化

異常在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

您正在使用字符串插值運算符(%),但你沒有給它插入任何東西。您需要將格式標籤插入到字符串中。

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

這是給你的錯誤

我覺得這裏應該是"The average price per portion is: %g " % mappp

+0

謝謝你們,ocho88那定了! –

3

有幾個錯誤在你的代碼

1)您可以通過使用動態更新標籤label.config()選項如:

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

2)標籤實例沒有屬性「推送」。

3)線:

menubar = Menu(window) 

window.config(menu=menubar) 

是無用的,因爲在你的程序

4)沒有菜單你爲什麼要使用按鈕和place()幾何馬槽pack()爲他人。 place()通常用於絕對佈局,最好避免。由於您正在使用所有其他小部件的包裝,因此最好使用包裝,即使是您的按鈕。

這裏是你的代碼修改所有這些錯誤:

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

+1對於很好的解釋:) –