как редактировать список словарей с помощью tkinter - PullRequest
0 голосов
/ 24 апреля 2018

Я хотел бы, чтобы у пользователя был способ редактировать списки, которые он создал, с помощью вкладки редактирования, которую я имею на панели инструментов.я понятия не имею, как я должен приблизиться к этому киту, все еще используя список

полного словарного словаря https://pastebin.com/6VAnZTyi

#************for defining what is in the list*******************    
class My_QueryString(tkinter.simpledialog._QueryString):

      def body(self, master):
          self.bind('<KP_Enter>', self.ok) # KeyPad Enter
          super().body(master)

def list_data(title, prompt, **kw):
    d = My_QueryString(title, prompt, **kw)
    return d.result
root = Tk()

#list
def liststagering(New_List):
   for item in New_List:
      print(item)
def New_List():
    new_list = myaskstring("list", "what do you want to name this list")
    List_Data = list_data("list","what should be in this list")
    if str(new_list):
        print(new_list)
        newList = dict()
        newList['title'] = new_list
        newList['listData'] = List_Data
        List_MASTER.append(newList)
        print("title : "+new_list)
        print(List_Data)

List_MASTER = []




lll=print (List_MASTER)
def printtext():


    T = Text(root)
    T.pack(expand=True, fill='both')
    printData = ""
    print(List_MASTER)
    for i in range(len(List_MASTER)):
        printData += List_MASTER[0]['title'] +"\n"+List_MASTER [i]['listData'] + "\n";
    T.insert(END,

            printData
            ,

            )

    for printData in T:
        T.delete(0,END)

1 Ответ

0 голосов
/ 24 апреля 2018

Редактировать словари внутри списка очень просто.

Сначала вам нужно получить словарь, вызвав индекс списка, в котором он находится.

Затем вы можете отредактировать словарькак обычно.

Взгляните на приведенные ниже примеры.Я написал несколько циклов for для чтения или редактирования словарей в списке.

list_of_dicts = [{"name":"Mike","age":30}, {"name":"Dave","age":22}, {"name":"Amber","age":24}]


for ndex, item in enumerate(list_of_dicts):
    # This will print the index number and dictionary at that index.
    print(ndex, item)


for item in list_of_dicts:
    # This will print each persons name and age of each dict in the list.
    print("The persons name is {} and they are {} years old!".format(item["name"], item["age"]))


for item in list_of_dicts:
    # this will update the age of each person by 1 year.
    item["age"] += 1
print(list_of_dicts)


# This will change Daves name to Mark.
list_of_dicts[1]["name"] = "Mark"
print(list_of_dicts[1])

Если вы запустите приведенный выше скрипт, вы должны получить следующие результаты в консоли:

0 {'name': 'Mike', 'age': 30}
1 {'name': 'Dave', 'age': 22}
2 {'name': 'Amber', 'age': 24}
The persons name is Mike and they are 30 years old!
The persons name is Dave and they are 22 years old!
The persons name is Amber and they are 24 years old!
[{'name': 'Mike', 'age': 31}, {'name': 'Dave', 'age': 23}, {'name': 'Amber', 'age': 25}]
{'name': 'Mark', 'age': 23}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...