英文:
How can I convert multiple label variables into a dictionary in tkinter using Python?
问题
你可以使用一个循环来创建这些标签,并将它们存储在一个字典中,然后可以通过字典来访问这些标签。以下是一个示例代码,演示如何使用 for 循环创建标签并将它们存储在字典中:
import tkinter as tk
base_frame = tk.Tk()
# 创建一个空字典来存储标签
label_dict = {}
# 定义行数和列数
rows = 6
cols = 5
# 使用双重循环创建标签并存储到字典中
for row in range(1, rows + 1):
for col in range(1, cols + 1):
label_name = f'answer_{row}_{col}'
label = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font=('Helvetica', 32, 'bold'))
label.grid(row=row, column=col, sticky='nesw', padx=2.5, pady=2.5)
label_dict[label_name] = label
# 访问字典中的标签示例
selected_label = label_dict['answer_2_3']
selected_label.config(text='New Text')
base_frame.mainloop()
这个示例中,我们首先创建一个空字典 label_dict
,然后使用双重循环创建标签,并将它们存储在字典中,键名使用了与之前的标签相同的命名。你可以通过字典的键来访问和操作相应的标签。在示例中,我们通过 label_dict['answer_2_3']
访问了字典中的一个标签,并修改了它的文本内容。
英文:
so I have these buttons in my program and I want them to be in a dictionary instead of them being in a separate value,
buttons are all the same for now , but they will change later in the code so thats why I'm making them separate values
answer_1_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_1_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_1_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_1_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_1_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_2_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_2_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_2_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_2_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_2_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_3_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_3_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_3_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_3_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_3_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_4_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_4_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_4_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_4_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_4_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_5_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_5_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_5_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_5_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_5_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_6_1 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_6_2 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_6_3 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_6_4 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_6_5 = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
answer_1_1.grid(row = 1, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_1_2.grid(row = 1, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_1_3.grid(row = 1, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_1_4.grid(row = 1, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_1_5.grid(row = 1, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_2_1.grid(row = 2, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_2_2.grid(row = 2, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_2_3.grid(row = 2, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_2_4.grid(row = 2, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_2_5.grid(row = 2, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_3_1.grid(row = 3, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_3_2.grid(row = 3, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_3_3.grid(row = 3, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_3_4.grid(row = 3, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_3_5.grid(row = 3, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_4_1.grid(row = 4, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_4_2.grid(row = 4, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_4_3.grid(row = 4, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_4_4.grid(row = 4, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_4_5.grid(row = 4, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_5_1.grid(row = 5, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_5_2.grid(row = 5, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_5_3.grid(row = 5, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_5_4.grid(row = 5, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_5_5.grid(row = 5, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_6_1.grid(row = 6, column = 1, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_6_2.grid(row = 6, column = 2, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_6_3.grid(row = 6, column = 3, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_6_4.grid(row = 6, column = 4, sticky = 'nesw', padx = 2.5, pady = 2.5)
answer_6_5.grid(row = 6, column = 5, sticky = 'nesw', padx = 2.5, pady = 2.5)
I want them to be like this :
dict = {'answer1': tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold')),
'answer2': tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold')),
...
}
any ideas on how to do this with a for loop and how to access the buttons in the dictionary?
答案1
得分: 2
我建议以下结构 - 创建一个嵌套循环,其中外部循环是问题,内部循环是每个问题的答案。对于每个答案,创建一个按钮(curr_button
)并将其保存在一个字典中。该字典是一个嵌套字典,其中每个问题都有一个键,该键本身是一个带有每个答案键的字典。
from itertools import product
from collections import defaultdict
num_questions = 6
answers_per_question = 4
buttons_dict = defaultdict(dict)
for q in range(1, num_questions+1):
for a in range(1, answers_per_question+1):
curr_button = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font=('Helvetica', 32, 'bold'))
curr_button.grid(row=q, column=a, sticky='nesw', padx=2.5, pady=2.5)
buttons_dict[q][a] = curr_button
英文:
I suggest the following structure - create a nested loop where the external loop is the questions and the internal one is the answers per question. For each answer, create a button (curr_button
) and save it in a dictionary. The dictionary is a nested dictionary where there is a key per question which is a dictionary itself with keys for each answer.
from itertools import product
from collections import defaultdict
num_questions = 6
answers_per_question = 4
buttons_dict = defaultdict(dict)
for q in range(1, num_questions+1):
for a in range(1, answers_per_question+1):
curr_button = tk.Label(base_frame, text='', fg='black', bg='white', highlightbackground='#d3d6da', highlightthickness=2, font = ('Helvetica', 32, 'bold'))
curr_button.grid(row = q, column = a, sticky = 'nesw', padx = 2.5, pady = 2.5)
buttons_dict[q][a]=curr_button
答案2
得分: 1
以下是代码的中文翻译部分:
# 为了演示如何编写一个高效的问答应用程序,举个例子。
# 只创建所需的内容并使用适当的技术来实现它。
import tkinter as tk
q_and_a = {
'你多大了?': [
16, # 0
18, # 1
21, # 2
48], # 3
'你住在哪里?': [
'美国',
'印度',
'英国',
'叙利亚'],
}
right_answer = {
'你多大了?': 0,
'你住在哪里?': 2,
}
def generate_q_and_a():
for k, v in q_and_a.items():
yield k, v
generator = generate_q_and_a()
def next_question():
try:
q, a = next(generator)
except StopIteration:
print('所有问题都已解决')
root.destroy()
else:
question.config(text=q)
for idx, child in enumerate(answer_frame.winfo_children()):
child.config(text=a[idx])
def answer_selected(n):
current_question = question.cget('text')
valid = n == right_answer[current_question]
if valid:
next_question()
else:
print('答案错误')
BACKGROUND = '灰色'
FOREGROUND = '黑色'
root = tk.Tk()
# 窗口的内容
question = tk.Label(
root, text='', bg=BACKGROUND, fg=FOREGROUND, relief=tk.RIDGE)
answer_frame = tk.Frame(
root, bg=BACKGROUND, borderwidth=2, relief=tk.SUNKEN)
# 设置窗口的几何属性
question.pack(fill=tk.X, expand=True)
answer_frame.pack(fill=tk.BOTH, expand=True)
# 回答选项的内容
choice_config = {
'master': answer_frame,
'text': '',
'relief': tk.RAISED,
'borderwidth': 1,
'background': '灰色',
'foreground': '白色',
}
for i in range(4):
callback = lambda n=i: answer_selected(n)
choice = tk.Button(**choice_config, command=callback)
choice.pack(fill=tk.X, expand=True)
# 启动应用程序
next_question()
root.mainloop()
注意:代码中的注释已被翻译成中文。
英文:
To give an example of how you basically code an efficient Q&A app.
Create just what you need and use the appropriate techs to achieve it.
For the sake of self-study, here is an example:
import tkinter as tk
q_and_a = {
'How old are you?' : [
16, #0
18, #1
21, #2
48],#3
'Where do you live?' : [
'USA',
'India',
'England',
'Syria'],
}
right_answer = {
'How old are you?' : 0,
'Where do you live?' : 2,
}
def generate_q_and_a():
for k,v in q_and_a.items():
yield k,v
generator = generate_q_and_a()
def next_question():
try:
q, a = next(generator)
except StopIteration:
print('all questions have solved')
root.destroy()
else:
question.config(text = q)
for idx,child in enumerate(answer_frame.winfo_children()):
child.config(text=a[idx])
def answer_selected(n):
current_question = question.cget('text')
valid = n == right_answer[current_question]
if valid:
next_question()
else:
print('wrong answer')
BACKGROUND = 'grey'
FOREGROUND = 'black'
root = tk.Tk()
#content of root
question = tk.Label(
root, text='', bg=BACKGROUND, fg=FOREGROUND, relief=tk.RIDGE)
answer_frame = tk.Frame(
root, bg = BACKGROUND, borderwidth=2, relief=tk.SUNKEN)
#geometry of root
question.pack(fill=tk.X, expand=True)
answer_frame.pack(fill=tk.BOTH, expand=True)
#content of answer_frame
choice_config = {
'master' : answer_frame,
'text' : '',
'relief' : tk.RAISED,
'borderwidth' : 1,
'background' : 'grey',
'foreground' : 'white',
}
for i in range(4):
callback = lambda n=i: answer_selected(n)
choice = tk.Button(**choice_config, command=callback)
choice.pack(fill=tk.X, expand=True)
#start application
next_question()
root.mainloop()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论