【问题标题】:Adding keys and values to the nested dictionary through EntryBoxes and accessing it through Combobox通过 EntryBoxes 向嵌套字典添加键和值,并通过 Combobox 访问它
【发布时间】:2021-07-31 19:34:21
【问题描述】:

是否可以通过Entrybox 添加新的键和值,然后立即通过Combobox 访问它,同时确保sub-keys 的新keyvalues 物理保存并附加到dictionary 就在它们被添加之后。当我print 新添加的keysub-keysvalues 时,一切似乎都很好,但dict1 itslef 和Comboboxvalues 没有变化。

代码如下:

from tkinter import *
from tkinter.ttk import Combobox

def add():

    dict1[entrybox.get()] = {'name_company': entrybox1.get(), 'country_company': entrybox2.get()}
    print(dict1)

dict1 = {"": {"name_company": 0,
    "country_company" : 0,},

    "Company1": {"name_company": "Company1 LTD",
    "country_company": "Germany"}}

window =Tk()

var1=StringVar()

entrybox = Entry(window) #adding main key ("Company1") as an example
entrybox.pack()

entrybox1 = Entry(window) #adding value of sub-key ("name_company")
entrybox1.pack()

entrybox2 = Entry(window) #adding value of sub-key ("country_company")
entrybox2.pack()

combo = Combobox(window, value=list(dict1.keys()), textvariable=dict1[var1.get()])
combo.pack()

button = Button(window, text="Add", command=add)
button.pack()

【问题讨论】:

    标签: python dictionary tkinter combobox tkinter-entry


    【解决方案1】:

    如果我正确理解了您的问题,我认为以下代码将为您提供所需的内容,或者让您接近最终目标。

    原始词干的问题是将条目值存储在某处,以便可以检索它们并将其用作组合框中的值,以及附加到字典中。

    作为一种解决方法,我使用了两个 .txt 文件,一个用于存储 Combobox 的值,另一个用于存储字典,每次按下添加按钮时都会更新。

    然后,Add 函数从 ComboValues.txt 文件中检索数据,将它们按字母顺序排序,并将它们分配给 Combobox。我并不是说这是最佳做法,但它应该满足您的要求。

    在旁注中,我要提供的提示是在导入模块时避免使用 *。它最终可能会变得混乱,尝试只导入你需要的东西,例如。 Combobox、Stringvar、Entry……等

    希望这会有所帮助,任何问题或澄清都可以联系我。

    import os
    from tkinter import Entry, StringVar, Tk, Button
    from tkinter.ttk import Combobox
    
    Root = Tk()
    #set combobox values to empty list
    ComboboxValue = []
    
    #String variables for dictionary values
    MainKey = StringVar()
    SubKey1 = StringVar()
    Subkey2 = StringVar()
    
    #Set dictionary values to open list
    Dict = {}
    
    #A place to save dictionary key values to read from later
    file = open('Combovalues.txt', 'a')
    
    #defining the function for adding entry values to dictionary
    def Add():
    
    #Second dictionary used to update original
        DictUpdated = {MainKey.get():{'name_company':SubKey1.get(), 'country_company':Subkey2.get()}}
    
    #Method to update original dictionary
        Dict.update(DictUpdated)
    
        print(Dict)
    
    #function to update combobox txt file with entry values
        with open('ComboValues.txt', 'a') as file:
            file.write('\n'+(str(SubKey1.get())+'\n'+(str(Subkey2.get()))))
            file.close
    
    #function to update Dictionary txt file with entry values        
        with open('Dictionary.txt', 'a') as file:
            file.write('\n'+str((Dict)))
            file.close
    
    #function to sort through entry values saved to combobox txt file, ready for assigning to combobox
    def ValueSource():
        with open('ComboValues.txt') as inFile:
            ComboboxValue = [line for line in inFile]
            ComboboxValue = sorted(ComboboxValue)
            return ComboboxValue
    
    #Function to retrieve values from combo txt file and assigned to combobox
    def GetUpdatedValues():
        Values = ValueSource()
        Root.Combobox['values'] = Values
    
    #Class to build GUI   
    class GUI ():
        def __init__(self, master):
            self.master = master
            master.EntryMainKey = Entry(Root, textvariable= MainKey).grid(row=0, columnspan=2)
            master.EntrySubKey1 = Entry(Root, textvariable= SubKey1).grid(row=1, columnspan=2)
            master.EntrySubKey2 = Entry(Root, textvariable= Subkey2).grid(row=2, columnspan=2)
            master.AddButton = Button(Root, text='Add', command=Add).grid(row=3, columnspan=2)
            master.Combobox = Combobox(Root, state='normal', postcommand=GetUpdatedValues)
            master.Combobox['values'] = ComboboxValue
            master.Combobox.grid(row=4, columnspan=2)
    
    #Mainloop function    
    def main():
        GUI(Root)
        Root.mainloop()
    
    main()
    

    【讨论】:

      猜你喜欢
      • 2011-05-13
      • 2013-01-19
      • 1970-01-01
      • 2016-11-19
      • 2015-01-06
      • 2016-10-21
      • 1970-01-01
      相关资源
      最近更新 更多