【问题标题】:How to create variables from dictionary keys?如何从字典键创建变量?
【发布时间】:2020-01-02 19:55:52
【问题描述】:

我有一本包含 tkinter 标签的字典,但下面我只包含字典的第一部分

当我使用变量时,在下面的示例中我没有收到任何错误。

from tkinter import *

root = Tk()

dic = {'response1':Label(root, bg='white')}

lbl = dic['response1']
lbl.config(text='Hey')
lbl.pack()

mainloop()

但是当我在没有变量的情况下这样做时,就像这样

from tkinter import *

root = Tk()

dic = {'response1':Label(root, bg='white')}

dic['response1'].config(text='Hey').pack()

mainloop()

我收到此错误

AttributeError: 'NoneType' object has no attribute 'pack'

从那以后,我需要为字典中的每个标签声明一个变量,这样我就可以避免这个错误。所以我在问如何为字典中的每个项目声明一个变量,其中键是变量名。所以response1 = Label(root, bg='white') 等等字典中的每个项目。

【问题讨论】:

  • 为什么不把它们作为字典值?
  • @wim 因为我需要它们作为变量类型,所以实际的 dict 包含我需要能够对其进行操作的 tkinter 按钮。如果我只是做 dict['key'] 我不能对它们执行操作
  • 您可以对局部变量执行哪些您无法对字典值执行的操作?
  • @wim 我将它们作为 tkinter 按钮,所以我需要能够像 .config(text='Some text')var1.pack() 这样的操作。否则,如果我执行dict['var1'].pack(),我会收到此错误:AttributeError: 'NoneType' object has no attribute 'pack'
  • @wim 问题已更新

标签: python python-3.x dictionary for-loop variables


【解决方案1】:

你不需要使用变量,你的错误实际上来自你试图使用.config的结果,到.pack。

尝试以下方法:

from tkinter import *

root = Tk()

dic = {'response1':Label(root, bg='white')}

dic['response1'].config(text='Hey')
dic['response1'].pack()

mainloop()

【讨论】:

  • 添加了一个小免责声明
  • 回答了问题的根本原因,而不是最初解决的问题。
  • @OsmosisJonesLoL 我以为我以前尝试过,但显然我没有,所以谢谢你,现在我知道该怎么做了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多