在Python3.5.2,Tkinter中,我正在创建一个基本的“菜单”系统,在这个系统中,人们会从菜单中订购一些东西,然后根据他们订购的商品的价格在底部创建账单。以下是目前为止的代码:
from tkinter import *
root = Tk()
root.geometry("500x500")
text1 = Label(root, text="Menu", font='Verdana, 15')
text1.pack()
coststr = StringVar()
cost = 0
coststr.set(str(cost))
menu = ["Burger", "Chips", "Milkshake"]
textln = Label(root, text="\n")
textln.pack()
def choiceburger():
global cost
global coststr
cost += 1.99
coststr.set(str(cost))
def choicechips():
global cost
global coststr
cost += 1.49
coststr.set(str(cost))
def choicemilkshake():
global cost
global coststr
cost += 0.99
coststr.set(str(cost))
burgerbutton = Button(root, text=" Burger £1.99 ", command=choiceburger)
burgerbutton.pack()
chipsbutton = Button(root, text=" Chips £1.49 ", command=choicechips)
chipsbutton.pack()
milksbutton = Button(root, text=" Milkshake £0.99 ", command=choicemilkshake)
milksbutton.pack()
textln = Label(root, text="\n")
textln.pack()
textln = Label(root, text="\n")
textln.pack()
textln = Label(root, text="\n")
textln.pack()
textln = Label(root, text="\n")
textln.pack()
textln = Label(root, text="\n")
textln.pack()
costlabel = Label(root, textvariable=coststr, font='Verdana, 15')
costlabel.pack()正如您所看到的,一旦单击按钮,就会将一个数字保存在底部,但没有任何货币符号(£或$)。因为我制作了textvariable=coststr,所以我无法编辑标签,将一个of或$标志放在成本的前面。有办法这样做吗?它已经在python中定义了吗?谢谢
发布于 2018-09-04 14:46:17
您需要在标签变量的设置中包括货币符号:
conststr.set(str(cost) + "£") # as suggested by @tobias_k in the comments为此,可以使用f字符串格式化coststr.set(str(cost)):
代之以
coststr.set(f'{cost} {currency_symbol}')其中currency_symbol是您的货币符号。
关于您的编辑:您可以使用decimal.Decimal类型来避免浮动不精确。
https://stackoverflow.com/questions/52168751
复制相似问题