1

I have to generate buttons (the number depends on the characters in the word), and so that each button, when pressed, performs its own separate function. Part code:

q = ['w', 'o', 'r', 'd']
s = (1, len(q))
a = np.zeros((s))
for i in range(0, a.shape[0]):
    for j in range(0, a.shape[1]):
        b = tk.Button(symbolsFrame, text= q[j], font = "Arial 12", bg = "white")#, command = lambda: btn_func())
        b.grid(row=i, column=j, padx = 3)
        v.append(b)

How can I assign each button, for example, so that when I click, the pressed letter is displayed in the console? When iterating over a list with a button, I get this result, but I don’t know what to do with it:

.!frame.!training.!frame.!button
.!frame.!training.!frame.!button2
.!frame.!training.!frame.!button3
.!frame.!training.!frame.!button4

if i change "command":

b = tk.Button(symbolsFrame, text= q[j], font = "Arial 12", bg = "white", command = lambda: print(q[j]))

When I click any button, send only last symbol:

.!frame.!training.!frame.!button
.!frame.!training.!frame.!button2
.!frame.!training.!frame.!button3
.!frame.!training.!frame.!button4
d
d
d
d
Andrej
  • 13
  • 3
  • 1
    In your button command, try: `lambda j=j: print(q[j])` – schwartz721 Jan 21 '20 at 00:31
  • Wow, its work, thank you very very much. But can you explain what is j = j ? – Andrej Jan 21 '20 at 00:41
  • 1
    When you were calling the command, it looked for the current value of j, which was used in the for loop. So the most recent value of j was j's last value after the for loop ended. j=j forces the computer to store the current value of j as the for loop is in progress, so it isn't looking up j's value at the end of the for loop. – schwartz721 Jan 21 '20 at 00:44

0 Answers0