3

i have created spin boxes using for loop when i tried to change the value of first spin box it will also reflect in another spin box. how can i rectify it. thanks in advance for answers.

 from tkinter import *
 win =Tk()
 frm1 = Frame(win,bg='sky blue')
 frm1.pack(fill='both',expand=1)
 products = [1,2,3,4,5]
 for prds in products:
     def change():
         print(entry11_cart.get())
     entry11_cart = Spinbox(frm1, textvariable=1, from_=1, to=10, command=change)
     entry11_cart.pack()
 win.mainloop()

[got this output]]click_to_view_output

i want to change the values of spin boxes separately and get() the values separately.

i need the changing value should be shown in spin box and the same value should print when we get() the spin box value.

Venkatesh
  • 33
  • 4
  • 1
    So you want multiple `Spinbox`es to be linked in a way where changing one of them changes the other? Look at what the `textvariable` parameter should be (hint a `tkinter` variable). – TheLizzard Jul 15 '21 at 09:04
  • no, you understood in opposite, i want multiple spin boxes using for loop but it should not be linked one with another each box values should be changed separately – Venkatesh Jul 15 '21 at 09:36

2 Answers2

1
from tkinter import *
w=Tk()
frm1 = Frame(w,bg='sky blue')
frm1.pack(fill='both',expand=1)
#the names of spinbox
l=["name_1","name_2"]
e=["apple","pine"]
#don't use for i in l
#it might assign all spinboxes' name to "i"
for i in range(len(l)):
    def change(i):
        print(l[i].get())
    e[i]=StringVar()
    l[i]=Spinbox(frm1, textvariable=e[i], from_=1, to=10, command=lambda i=i: change(i))
    l[i].pack()
    print(l[i])
w.mainloop()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • no, it changes the value of the spin box only. but i want the original value to be printed on every single up or down click – Venkatesh Jul 15 '21 at 09:24
  • @Venkatesh I updated this answer. It should work now. Can you please try it again? – TheLizzard Jul 15 '21 at 09:39
  • @TheLizzard, yep, it works. Also, you can add ```print(l[i],':',li[i].get())``` to prove that the spin boxes are different –  Jul 15 '21 at 10:21
0

You need to dynamically change the text variable for each -

spin_num = 0
for prds in products:
     spin_num += 1
     def change():
          print(entry.get())
     entry = Spinbox(frm1, textvariable=f'{spin_num}', from_=1, to=10, command=change)
     entry.pack()

This will change value of the text variable for each spin_box. This will work

PCM
  • 2,881
  • 2
  • 8
  • 30
  • 1
    This code doesn't work because of the same reason [this](https://stackoverflow.com/q/10865116/11106801) doesn't work. The `change` function uses the last entry. – TheLizzard Jul 15 '21 at 08:59
  • 1
    Also the `textvariable` parameter is for a `tkinter` variable like `IntVar`, `StringVar`, `DoubleVar`, or `BooleanVar` not for a string. – TheLizzard Jul 15 '21 at 09:00