希望是一个快速的,但我知道它不会。我正在为自己编写一个小应用程序,我收集银币,未来我将做的不仅仅是银币,但现在我想记录我所拥有的,计划是使用组合框仅显示每个子组合框所需的数据
每个硬币的数据是(金属类型、国家、硬币类型、年份、纯度)如下所示,我有每个金属类型(金、银、铂、钯)的国家列表,每个国家至少有一枚硬币,并非所有国家都有所有金属类型,一些国家有更多。算上它,组合框事件将至少有54条if语句
有没有更合适的方法来管理这些数据,也许是字典?
{"Australia1": {"Silver": "Red Kangaroo", "Koala", "Kookaburra"}}
{"Australia2": {"Gold": "Gold Nugget", "Dragon Rectangular Coin"}}
{"Australia3": {"Platinum": "coin1", "coin2"}}
等等
from tkinter import *
from tkinter import ttk
def draw_main_window():
metals = ['Palladium',
'Platinum',
'Gold',
'Silver']
gold_country = ["Austria",
"Canada",
"China",
"Iran",
"Isle of Man",
"Israel",
"Kazakhstan",
"Malaysia",
"Malta",
"Mexico",
"New Zealand",
"Poland",
"Russia",
"Somalia",
"South Africa",
"Ukraine",
"United Kingdom",
"United States"]
silver_country = ["Armenia",
"Australia",
"Austria",
"Canada",
"China",
"Congo (Republic)",
"Cook Islands",
"Isle of Man",
"Mexico",
"New Zealand",
"Niue/Fiji",
"Russia",
"Rwanda",
"Serbia",
"Somalia",
"South Africa",
"South Korea",
"Ukraine",
"United Kingdom",
"United States"]
palladium_list = ["Australia",
"Canada",
"China",
"Portugal",
"Russia",
"United States"]
platinum_list = ["Australia",
"Austria",
"Canada",
"Isle of Man",
"United Kingdom",
"United States"]
def metal_click(event):
metal_value = cmb_metal.get()
if metal_value == "Palladium":
cmb_country['values'] = palladium_list
if metal_value == "Platinum":
cmb_country['values'] = platinum_list
if metal_value == "Gold":
cmb_country['values'] = gold_country
if metal_value == "Silver":
cmb_country['values'] = silver_country
def country_click(event):
current_value = cmb_country.get()
if current_value == "Australia":
cmb_type['values'] = "Emu"
if current_value == "Canada":
cmb_type['values'] = "Palladium Maple Leaf"
root = Tk()
root.geometry("640x480")
root.title("Silver-Inventory")
Label(root, text="Metal").grid(column=0, row=0)
Label(root, text="Country").grid(column=0, row=1)
Label(root, text="Coin Type").grid(column=0, row=2)
Label(root, text="Year").grid(column=0, row=3)
Label(root, text="Metal").grid(column=0, row=4)
Label(root, text="Fineness").grid(column=0, row=5)
cmb_metal = ttk.Combobox(root, values=metals)
cmb_metal.grid(column=1, row=0)
cmb_metal.bind("<<ComboboxSelected>>", metal_click)
cmb_country = ttk.Combobox(root)
cmb_country.grid(column=1, row=1)
cmb_country.bind("<<ComboboxSelected>>", country_click)
cmb_type = ttk.Combobox(root)
cmb_type.grid(column=1, row=2)
root.mainloop()
draw_main_window()
2条答案
按热度按时间zte4gxcn1#
您通常可以转换一长串的
if
语句转换为简单的字典查找。例如,与此相反:
... 可以使用字典在金属值和列表之间创建Map:
hmae6n7t2#
我认为嵌套字典是一种很好的方法。我一直很喜欢@aaron hall's
Vividict
类在他对问题的回答中显示了实现嵌套字典的最佳方法是什么?因为它使构建它们变得非常容易。这个概念来自perl,被称为“自活化”。下面演示了如何使用它保存您拥有的数据类型:
下面是创建的嵌套字典: