繁体   English   中英

我如何创建一个Python字典,通过tkinter文本框从用户那里获取其值和键?

[英]How can I create a python dictionary that gets its values and keys from the user through tkinter text boxes?

我是Python的新手,我真的不知道从哪里开始。 我可以轻松地追加字典以接受一个新变量,但是“ .append()”仅允许一个参数,因此我不确定如何在同一条目中包含另一个变量的键。

在python中,您可以将键和值添加到字典中,如下所示:

dict = {} # create an empty dictionary
dict["key1"]  = "value1" # string to a key
dict["key2"]  = 0 # number to a key
dict["key3"]  = ["value1", "value2"] # array to a key
dict["key4"]  = {"key4a": "value4a"} # dictionary to a key

在您的特定情况下,您可以:

•在您的init中将空字典设置为class属性

import tkinter as tk

class SampleApp(tk.Tk):
   def __init__(self):
       self.dict = {}
       # the rest of your application

•创建一种向此字典添加键和值的方法

import tkinter as tk

class SampleApp(tk.Tk):
   def __init__(self):
       self.dict = {}
       # the rest of your application

   def append_to_dict(key, value):
       self.dict[key] = value

然后,您可以在应用程序中触发此方法,并将要添加为键和值的元素传递给该方法。

暂无
暂无

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

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