【问题标题】:Python Tkinter Using CurrencyPython Tkinter 使用货币
【发布时间】:2018-09-04 23:01:38
【问题描述】:

在 Python 3.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,因此我无法编辑标签以在成本前添加 £ 或 $ 符号。有没有办法做到这一点?它已经在python中定义了吗?谢谢

【问题讨论】:

  • 使用 f 字符串格式化coststr.set(str(cost)): coststr.set(f'{cost} {currency_symbol}')

标签: python tkinter


【解决方案1】:

您需要将货币符号包含在标签变量的设置中:

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 类型来避免浮点不精确。

【讨论】:

  • 我还发现,当添加多个项目时,由于在大约 7 或 8 次点击后价格标签不规则(0.49、0.99),账单会变成一个长十进制数字,如 4.000000009 或 5.899999999999。无论如何也要阻止这一切?将其设置为仅小数点后 2 位?
  • 我添加了一个关于使用十进制模块进行货币算术的注释。
  • 这不是只有在 Python 3.6+ 中才有可能吗?据说OP使用的是3.5。此外,使用 f 字符串在这里并不真正相关,而只是将符号放回字符串中,例如conststr.set(str(cost) + "£")conststr.set("%.2f £" % cost) 也可以。
  • 好点@tobias_k,我将您的评论作为我回答的一部分,感谢您的宝贵意见。
猜你喜欢
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 2022-07-12
  • 2015-07-27
  • 2014-08-01
  • 2015-08-04
  • 1970-01-01
  • 2019-02-23
相关资源
最近更新 更多