我還是新手(不到 1 年的經驗)。我想制作一個簡單的 POS 程式,但我不知道如何從回圈中獲取值并更新標簽。我試圖從我在互聯網上搜索的內容中學習,但無法獲得我想要的結果。這是下面的代碼。
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()```
uj5u.com熱心網友回復:
- 請不要
command=plus(i)在grid函式中使用。把它寫在tk.Button(...). - 你可以使用
command=(lambda item=i: plus(item)),但不能command=plus(i)。如果沒有引數,可以使用command=plus. - 用于
xxx.config()更新元素。
這段代碼有效嗎?
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/512057.html
