首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用货币的Python Tkinter

使用货币的Python Tkinter
EN

Stack Overflow用户
提问于 2018-09-04 14:38:58
回答 1查看 768关注 0票数 0

在Python3.5.2,Tkinter中,我正在创建一个基本的“菜单”系统,在这个系统中,人们会从菜单中订购一些东西,然后根据他们订购的商品的价格在底部创建账单。以下是目前为止的代码:

代码语言:javascript
复制
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中定义了吗?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-04 14:46:17

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

代码语言:javascript
复制
conststr.set(str(cost) + "£")      # as suggested by @tobias_k in the comments

为此,可以使用f字符串格式化coststr.set(str(cost))

代之以

代码语言:javascript
复制
coststr.set(f'{cost} {currency_symbol}')

其中currency_symbol是您的货币符号。

关于您的编辑:您可以使用decimal.Decimal类型来避免浮动不精确。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52168751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档