【问题标题】:how to sum up total from a dictionary如何从字典中总结总数
【发布时间】:2019-04-28 18:02:31
【问题描述】:

我正在尝试制作一个与在商店接受订单相关的程序。整个代码是关于下订单的页面,然后创建标签列表。一切都做得很好,但是我无法获得总价格。这是我的代码:

def blnclick():
    n=0
    uprice = price.get()
    uitem = item.get()
    order = {'items': uitem, 'price': uprice}
    lab = order['items']
    lab1 = order['price']
    total = int(lab1)
    c = Canvas(canvas_frme, bg='white', bd=10, width=10, height=50)
    c.pack()
    for values in order:
        Label(c, text=lab, bg='white', font=('candara', 19)).grid(row=n, column=0)
        Label(c, text=lab1, bg='white', font=('candara', 19)).grid(row=n, column=1)
        totSum.set(total)
        total = total+total

提前感谢您的帮助。

更新:我认为代码不擅长处理字典,因为每次我尝试使用新代码来汇总价格时,它总是总结输入一次的数字,然后插入新条目后重置。任何事物。 请注意,我仍然是 python 的学习者/学生,因此代码中的任何工作更改都是可以接受的。

update#2 当你们去购物时,您会购买多件商品,然后商品清单会显示总金额。我正在努力做到这一点。随意根据您的需要更改代码,因为我是一名学习者,并且我经常犯错误。谢谢大家

【问题讨论】:

  • 你应该有类变量来保持总数 - 即。 self.total.value。现在您创建不能保留旧值的局部变量 total。此外,您将新值分配给总计 total = int(lab1),因此它会删除 olvder 值。
  • 要将小部件添加到画布,您必须使用 canvas_window((x,y), widget). We use pack()/grid()` 将小部件添加到其他小部件 - 例如 Frame。现在你有一些混乱。

标签: python python-3.x tkinter


【解决方案1】:

我只会使用列表推导来获取列表中的所有数字并将它们相加

# sample dict 
d = {"one":1, "two":2, "three":3}

# for each key, get it's "price", sum list
x = sum([d[k] for k in d])

【讨论】:

  • 我不认为它会起作用,因为字典不会保存我输入的所有值,它只会创建该条目的标签。我认为当我插入一个新条目时,前一个条目会被删除,因此列表中的总和不会有用(根据我的猜测!)
  • 我不确定你的意思——你的意思是如果有一个订单包含多个相同的东西它不起作用?即,如果你有一个 {"Jacket": 40, "Jacket": 45}?
  • 我在这里尝试的是创建多个值。例如:当您去商店购买多件商品,然后创建商品列表时,我正试图在这里准确地执行此操作,我正在尝试创建多个项目的列表,具体而言,在关键项目:价格中,我必须存储以下订单:“衬衫:30 美元”、“夹克:50 美元”、“T 恤:25 美元”等。
  • 我明白了。看起来您需要对每个类别的项目进行字典,按照我向您展示的相同方式获取总数,然后将它们相加。
【解决方案2】:

使用sum 真的很简单:

total = sum(int(value) for key, value in order.items())

【讨论】:

  • 它显示一个错误:“+ 的不支持的操作数类型:'int' 和 'str'”
  • @AndriousPrime 检查我编辑的答案。你的价格只是字符串,所以需要先转换它们。
【解决方案3】:

目前您创建的局部变量 total 不能保留旧值。
除了您分配新值 total = int(lab1) 之外,它会删除旧值。

您需要全局变量 (global total) 来始终保持总值。
然后您可以将新值添加到 total 以保留旧值。

要将小部件添加到画布,您必须使用canvas_window((x,y), widget)
我们使用pack()/grid() 将小部件添加到其他小部件,如Frame。现在你有一些混乱。

我使用 Frame 并跳过了颜色和字体等不重要的选项。

#global variable 
total = 0 # value as start

# to keep all orderde items
#order = []

# to display total value 
#total_label = Label(root, text='')
#total_label.pack()

def blnclick():

    uprice = price.get()
    uitem = item.get()

    global total
    total += int(uprice) # add to global value

    # display new total
    #total_label['text'] = str(total)

    # add ordered item to list
    #order.append({'item': uitem, 'price': uprice})

    frame = Frame(canvas_frme)
    frame.pack()

    l = Label(frame, text=uprice)
    l.grid(row=0, column=0)

    l = Label(frame, text=uitem)
    l.grid(row=1, column=1)

编辑:

完整的工作示例

import tkinter as tk

# --- functions ---

def on_button_add():

    uprice = price_entry.get()
    uitem = item_entry.get()

    global total
    total += int(uprice) # add to class value

    # display new total
    total_label['text'] = str(total)

    # add ordered item to list
    order.append({'item': uitem, 'price': uprice})
    print('full order:', order)
    print('total:', total)

    number = len(order)

    l = tk.Label(frame_order, text=uitem)
    l.grid(row=number, column=0)

    l = tk.Label(frame_order, text=uprice)
    l.grid(row=number, column=1)

# --- main ---

# values at start
total = 0
order = []

root = tk.Tk()

#--- entry for new item ---

l = tk.Label(root, text='Item:')
l.grid(row=0, column=0)

item_entry = tk.Entry(root)
item_entry.grid(row=0, column=1)

l = tk.Label(root, text='Price:')
l.grid(row=1, column=0)

price_entry = tk.Entry(root)
price_entry.grid(row=1, column=1)

button = tk.Button(root, text='ADD', command=on_button_add)
button.grid(row=2, column=0, columnspan=2)

#--- frame with order ---

frame_order = tk.Frame(root)
frame_order.grid(row=3, column=0, columnspan=2)

l = tk.Label(frame_order, text="Items")
l.grid(row=0, column=0)

l = tk.Label(frame_order, text="Prices")
l.grid(row=0, column=1)

#--- total ---

# to display total value 
l = tk.Label(root, text='Total:')
l.grid(row=4, column=0)

# to display total value 
total_label = tk.Label(root, text='')
total_label.grid(row=4, column=1)

root.mainloop()

【讨论】:

  • 此代码可以按照我的要求正常工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2016-09-17
相关资源
最近更新 更多