简体   繁体   English

每次用户单击按钮时如何更新字典中的键值?

[英]How to update key-value in dictionary everytime the user clicks the button?

I can't update key-value in dictionary upon clicking the save button, but I don't know what's wrong with my code? 单击save按钮后,我无法更新字典中的键值,但是我不知道我的代码有什么问题?

This is for my little project, I want to try writing code to create an app(for my personal use) using Tkinter to set and get data from entries and save to a csv file. 这是为我的小项目,我想尝试编写代码以使用Tkinter设置和获取条目数据并将其保存到csv文件,以创建一个应用程序(供我个人使用)。 But I've been stuck on updating my dictionary. 但是我一直在更新字典。 I've tried making my dict a global variable, but it's still kept on deleting old key-value from the previous click. 我尝试将dict设置为全局变量,但仍继续删除上一次点击的旧键值。 At some point during my trial-and-error, there's an error stating that my dict variable isn't defined. 在反复试验的过程中,有时会出现错误,指出我的dict变量未定义。

def Save(self):

    self.new_first_name = self.first_name.get()
    self.new_last_name = self.last_name.get()
    self.new_id = self.id.get()
    self.new_age = self.age.get()

    self.dirname = "J:/Webcam"
    self.new_dict = {}

    def create_dict():
        global old_dict
        if 'old_dict' not in globals():
            global old_dict
            old_dict = {"ID": None, "First_Name" : None, "Last_Name": None, "Age": None}
        else:
            pass
        return old_dict
    create_dict()

    self.new_dict['ID'] = self.new_id
    self.new_dict['First_Name'] = self.new_first_name
    self.new_dict['Last_Name'] = self.new_last_name
    self.new_dict['Age'] = self.new_age

    old_dict.update(self.new_dict)

    # os.chdir(self.dirname)
    # w = csv.writer(open("output.csv", "w"))
    # for key, val in old_dict.items():
    #     w.writerow([key, val])
    return old_dict

This is the result after I clicked the 'save' button two times. 这是我两次单击“保存”按钮后的结果。

{'ID': 'AA', 'First_Name': 'AA', 'Last_Name': 'AA', 'Age': 'AA'}

{'ID': 'BB', 'First_Name': 'BB', 'Last_Name': 'BB', 'Age': 'BB'}

What I want is like this: 我想要的是这样的:

{'ID': ['AA','BB'], 'First_Name': ['AA','BB'], 'Last_Name': ['AA','BB'], 'Age': ['AA','BB']}

This problem is not specifically a TkInter problem. 此问题不是特定的TkInter问题。 You can reproduce similar behavior with a python command-line. 您可以使用python命令行重现类似的行为。

Try this: 尝试这个:

>>> old_dict = {}
>>> old_dict['ID'] = 'AA'
>>> old_dict['ID'] = 'BB'
>>> old_dict
{'ID': 'BB'}

That's because you first set the key 'ID' 's value to 'AA', and then to 'BB'. 这是因为您首先将键'ID'的值设置为“ AA”,然后将其设置为“ BB”。

What you want to do is make the dictionary contain a list for each key, and always append to those lists. 您要做的是使字典包含每个键的列表,并始终将其追加到这些列表中。

>>> old_dict = {}
>>> old_dict['ID'] = []
>>> old_dict['ID'].append('AA')
>>> old_dict['ID'].append('BB')
>>> old_dict
{'ID': ['AA', 'BB']}

You could save yourself a little effort by using collections.defaultdict : 您可以使用collections.defaultdict节省一些精力:

>>> import collections
>>> old_dict = collections.defaultdict(list)
>>> old_dict['ID'].append('AA')
>>> old_dict['ID'].append('BB')
>>> old_dict
{'ID': ['AA', 'BB']}

All defaultdict does, the way this code is specified, is create a list for you for any key that doesn't already have a value. 所有defaultdict都以指定此代码的方式为您创建一个列表,该列表为您没有值的任何键。

If you apply this kind of logic to your code, you should find that tkInter is behaving the way you want it to. 如果将这种逻辑应用于代码,则应该发现tkInter的行为符合您的期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM