Home > Software engineering >  How to generate tkinter's element with for dict/list and save their value and update them?
How to generate tkinter's element with for dict/list and save their value and update them?

Time:10-07

i'm still new to code (less than 1 year experience). I want to make a simple POS program but i can't figuring how to get the value from the loop and update the labels. I tried to learn from what i search in the internet but not able to get the result i wanted. Here is the code below.


item = ["A", "B", "C"]

labels = {}
lvalues = {}
buttons = {}
values = {}


fcount = 0

app = tk.Tk()

def plus(item):
    val = values[item]
    val  = 1
    values[item] = val 
    print(lvalues[item])

for i in item:
    values[i] = 0
    labels[i] = tk.Label(app, text=i)
    labels[i].grid(row=fcount, column=0)
    lvalues[i] = tk.Label(app, text=values[i])
    lvalues[i].grid(row=fcount, column=1)
    buttons[i] = tk.Button(app, text=" ")
    buttons[i].grid(row=fcount, column=2, command=plus(i))
    fcount  = 1
    
print(labels)
print(values)

app.mainloop()```

CodePudding user response:

  1. Please don't use command=plus(i) in the grid function. write it in tk.Button(...).
  2. You can use command=(lambda item=i: plus(item)), but not command=plus(i). If there is no parameters, you can use command=plus.
  3. Use xxx.config() to update the elements.

Does this code work?

import tkinter as tk

item = ["A", "B", "C"]

labels = {}
lvalues = {}
buttons = {}
values = {}


fcount = 0

app = tk.Tk()

def plus(item):
    values[item]  = 1
    lvalues[item].config(text=str(values[item]))
    print(lvalues[item])

for i in item:
    values[i] = 0
    labels[i] = tk.Label(app, text=i)
    labels[i].grid(row=fcount, column=0)
    lvalues[i] = tk.Label(app, text=values[i])
    lvalues[i].grid(row=fcount, column=1)
    buttons[i] = tk.Button(app, text=" ", command=(lambda item=i: plus(item)))
    buttons[i].grid(row=fcount, column=2)
    fcount  = 1
    
print(labels)
print(values)

app.mainloop()
  • Related