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:
- Please don't use
command=plus(i)
in thegrid
function. write it intk.Button(...)
. - You can use
command=(lambda item=i: plus(item))
, but notcommand=plus(i)
. If there is no parameters, you can usecommand=plus
. - 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()