首页 > 解决方案 > 如何访问动态变量?

问题描述

我在我的 tkinter 项目中创建了动态变量,但我无法访问它,我该怎么做?

dict_ndfitemcostcategory = {}
for ndicc in range(2, 133):
    # self.neighborhood_details_item_cost_category_entry_2  - starting point
    dict_ndfitemcostcategory["self.neighborhood_details_item_cost_category_entry" + "_" + str(ndicc)] = tk.Text(self.frame, height=2, width=25, bg='alice blue', wrap=tk.WORD)
    dict_ndfitemcostcategory["self.neighborhood_details_item_cost_category_entry" + "_" + str(ndicc)].grid(row=ndicc, column=3, padx=5, pady = 4)

我试图运行:

self.neighborhood_details_item_cost_category_entry_2.insert(tk.END, "asd")

但是好像找不到: AttributeError: 'Neighborhood_Details' object has no attribute 'dict_ndn'

标签: pythonooptkinter

解决方案


您没有定义动态变量;您只是在定义一个dict函数返回时超出范围的普通函数。字典本身应该是一个实例属性,以所需的“动态”属性作为键。

self.dict_ndfitemcostcategory = {}
for ndicc in range(2, 133):   
    key = "neighborhood_details_item_cost_category_entry" + "_" + str(ndicc)
    self.dict_ndfitemcostcategory[key] = tk.Text(self.frame, height=2, width=25, bg='alice blue', wrap=tk.WORD)
    self.dict_ndfitemcostcategory[key].grid(row=ndicc, column=3, padx=5, pady = 4)

然后

self.dict_ndfitemcostcategory["neighborhood_details_item_cost_category_entry_2"].insert(tk.END, "asd")

推荐阅读