配置自动生成的按钮以显示不同的值

configuring auto-generated buttons to display different values

我使用循环将 4 个值的列表转换为一组按钮。我需要覆盖这些按钮的文本以包含另一个列表的值(在本例中为 Ans2)。任何帮助将不胜感激。

import tkinter as tk

root = tk.Tk()

def NextQuestion():
    print("this is where i need to configure the buttons to contain values from list - Ans2")

Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]

AnsNo = 0
r = 0
c = 0
for x in range(len(Ans1)):
    AnsBtn = tk.Button(root, text=(Ans1[AnsNo]), command = NextQuestion)
    AnsBtn.grid(row=r, column=c)
    AnsNo = AnsNo+1
    if r == 1:
        c = 1
        r = 0
    else:
        r = r+1

首先,您需要将按钮存储在某个地方,以便可以访问并更改它们。然后你只需访问他们的文本变量并更改它。

import tkinter as tk

root = tk.Tk()

def NextQuestion():
    for i, button in enumerate(buttons):
        button["text"] = Ans2[i]

Ans1 = [6,5,32,7]
Ans2 = [4,9,3,75]

buttons = []

AnsNo = 0
r = 0
c = 0
for i,answer in enumerate(Ans1):
    AnsBtn = tk.Button(root, text=(answer), command = NextQuestion)
    AnsBtn.grid(row=r, column=c)
    buttons.append(AnsBtn)
    if r == 1:
        c = 1
        r = 0
    else:
        r = r+1

root.mainloop()