-1

I'm trying to create simple GUI like this:

  • three set of label, entry, and READ button, one set for one row
  • when READ button is pressed, the value of entry will be displayed on label. But all Read button only read from the last entry and displayed on last label. Here is my script:
import tkinter as tk

main = tk.Tk()
label = [None]*3
entry = [None]*3


for j in range(3):
    label[j] = tk.StringVar()
    tk.Label(main, textvariable = label[j], relief = 'raised', width = 7).place(x = 5, y = 40+30*j)
    entry[j] = tk.Entry(main, width=8)
    entry[j].place(x=80, y=40 + 30 * j)
    tk.Button(main, text="READ", pady=0, padx=10, command= lambda: label[j].set(entry[j].get())).place(x=150, y=40 + 30 * j)
    

main.mainloop()

1 Answers1

0

The problem with the code you sent is that the value of j is changing with the loop, so as the loop ends, all of your buttons and lables take the value of j as 3 (thats because when your loop ends, j has the value "3") so that means all of your lables and buttons are using the last label. An easy fix would be to manually set label[j] and entry[j] to some other variable, then apply the command.
Something like this :
lambda x=label[j], y=entry[j]: x.set(y.get()) Here I first set label[j] to x and entry[j] to y and then change the values inside lambda.

import tkinter as tk

main = tk.Tk()
label = [None]*3
entry = [None]*3
read = [None]*3

for j in range(3):
    label[j] = tk.StringVar()
    tk.Label(main, textvariable = label[j], relief = 'raised', width = 7).place(x = 5, y = 40+30*j)
    entry[j] = tk.Entry(main, width=8)
    entry[j].place(x=80, y=40 + 30 * j)
    read[j] = tk.Button(main, text="READ", pady=0, padx=10, command= lambda x=label[j], y=entry[j]: x.set(y.get()))
    read[j].place(x=150, y=40 + 30 * j)

main.mainloop()