将项从字典的字典添加到Listbox,Tkinter,Python列表中

2024-04-30 06:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我用pythonttkinter制作了一个三重列表框小部件。在

首先,我有一个这样的口述:

testDict = {'animal': {'mammal': ['mouse', 'cat'], 'reptile': ['lizard', 'snake']}, 'food': {'meat': ['bacon', 'lamb', 'beef'], 'fruit': ['apple', 'pear', 'banana', 'kiwi']}}

现在我希望能够:第一步。点击“添加主题”按钮,将“动物”和“食物”作为主题添加到第一个列表框中。在

第二步。在第一个列表框中选择一个键,然后单击“添加类型”将相应的类型添加到第二个列表框中,例如“水果”和“肉类”或“哺乳动物”和“爬行动物”。在

第三步。从第二个列表框中选择一个类型,并将相应的项添加到第三个列表框中,例如:“lizard”、“snake”或“apple”、“pear”、“banana”、“kiwi”等

我被困在第三步。在

我的代码:

^{pr2}$

你能帮我修一下addName按钮使它正常工作吗? 任何帮助都将不胜感激。在

提前谢谢!在


Tags: 类型apple主题部件按钮bananapearsnake
1条回答
网友
1楼 · 发布于 2024-04-30 06:21:39

斯托弗尔的建议很管用。感谢大家的意见。在

我把正确的代码放在这里:

import tkinter as tk

from tkinter import *

root = Tk()

testDict = {'animal': {'mammal': ['mouse', 'cat'], 'reptile': ['lizard', 'snake']}, 'food': {'meat': ['bacon', 'lamb', 'beef'], 'fruit': ['apple', 'pear', 'banana', 'kiwi']}}

Box1 = tk.Listbox(height=8, width=50, borderwidth=2)
Box1.pack()
Box2 = tk.Listbox(height=8, width=50, borderwidth=2)
Box2.pack()
Box3 = tk.Listbox(height=8, width=50, borderwidth=2)
Box3.pack()


def addTheme():
    Box1.delete(0, END) 
    for themeName in testDict:
            Box1.insert(END, themeName)

def addType():
    getKey1 = str((Box1.get(ACTIVE)))
    Box1.get(ANCHOR)
    Box2.delete(0, END) 
    for itemType in testDict[getKey1]:            
        Box2.insert(END, itemType)



def addName():

    getKey1_for_Box2 = str((Box1.get(ACTIVE)))
    getKey2 = str((Box2.get(ACTIVE)))
    Box2.get(ANCHOR)
    Box3.delete(0, END)
    for itemName2 in testDict[getKey1_for_Box2][getKey2]:
        Box3.insert(END, itemName2)



themeButton = tk.Button( text = "Add Theme", command= lambda: addTheme())
themeButton.pack(side=TOP)

typeButton = tk.Button(text = "Add Type", command= lambda: addType())
typeButton.pack(side=TOP)

nameButton = tk.Button(text = "Add Name", command= lambda: addName())
nameButton.pack(side=TOP)


root.mainloop()

相关问题 更多 >