Home > Net >  configuring auto-generated buttons to display different values
configuring auto-generated buttons to display different values

Time:12-28

I have used a loop to turn a list of 4 values into a set of buttons. I need to overwrite the text of these buttons to contain the values of another list (in this case Ans2). any help would be greatly appreciated.

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

CodePudding user response:

First you need to store the buttons somewhere so they can be accessed to be changed. Then you just access their text variable and change it.

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()
  • Related