【问题标题】:How to get a listbox to print a dictionaries containig item names and prices- Python如何让列表框打印包含项目名称和价格的字典 - Python
【发布时间】:2020-08-25 15:23:46
【问题描述】:

所以我有一本存储食品及其价格的字典,如下所示:

Menu = {"Mozerella":"£3.50", "Haiwann":"£3.99", "New York Style":"£4.10", "Chicken Gougons":"£3.80"}

但是,当我运行这个 sn-p

choices = Menu
tkvar.set("Mozerella")
popupMenu = OptionMenu(Menu_Screen, tkvar, *choices)

它在列表框中仅显示为项目名称,没有附加价格。 如何将商品及其附加的价格添加到列表框中。

【问题讨论】:

    标签: python dictionary tkinter listbox


    【解决方案1】:

    要组合商品和价格,您可以使用列表推导来合并字典键和值。这将创建一个新列表以在下拉列表中使用。

    试试这个代码:

    import tkinter as tkr
    root = tkr.Tk()
    
    # textbox for testing
    selText=tkr.StringVar()
    e1=tkr.Entry(root, textvariable=selText, width=42)
    e1.grid(row=0, column=1)
    
    def OptionMenu_Select(e): # user selection changed
       selText.set(tkvar.get())  # update textbox
    
    Menu = {"Mozerella":"$3.50", "Haiwann":"$3.99", "New York Style":"$4.10", "Chicken Gougons":"$3.80"}
    choices = [m + "  " + Menu[m] for m in Menu]  # combine item and price
    
    tkvar=tkr.StringVar()
    tkvar.set(choices[0])  # set dropdown
    selText.set(choices[0])  # set text box  
    popupMenu = tkr.OptionMenu(root, tkvar, *choices, command = OptionMenu_Select)
    popupMenu.grid(row=1, column=1)
    
    root.mainloop()
    

    【讨论】:

    • 谢谢,我已经有了大部分代码,所以我所要做的就是用你给的替换我的选择 = 并将我的 tkvar.set 更改为选择 [0]。这是一种享受。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2017-08-20
    • 2018-08-14
    • 1970-01-01
    相关资源
    最近更新 更多