【发布时间】: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