如果我正确理解了您的问题,我认为以下代码将为您提供所需的内容,或者让您接近最终目标。
原始词干的问题是将条目值存储在某处,以便可以检索它们并将其用作组合框中的值,以及附加到字典中。
作为一种解决方法,我使用了两个 .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()