gpt4 book ai didi

python - 使用 Python 和 Tkinter 格式化字符串

转载 作者:行者123 更新时间:2023-11-28 21:54:13 24 4
gpt4 key购买 nike

我正在尝试创建我的第一个带有图形用户界面的程序。我得到的错误如下:

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

最佳答案

你的代码有几个错误

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

关于python - 使用 Python 和 Tkinter 格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24524804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com