簡體   English   中英

如何從字典鍵創建變量?

[英]How to create variables from dictionary keys?

我有一本包含 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')等等。

您不需要使用變量,您的錯誤實際上來自您嘗試將 .config 的結果用於 .pack。

請嘗試以下操作:

from tkinter import *

root = Tk()

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

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

mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM