2 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果要?jiǎng)?chuàng)建多行小部件,可以創(chuàng)建一個(gè)數(shù)組來(lái)存儲(chǔ)小部件引用,并使用循環(huán)在網(wǎng)格中創(chuàng)建小部件。
import tkinter as tk
root = tk.Tk()
root.geometry('850x450')
lstentry = [] # all entries
lstlabel = [] # all labels
for ctr in range(5): # 5 rows
var1 = tk.StringVar()
t1 = tk.Entry(root, textvariable=var1).grid(row=ctr+1,column=1)
var2 = tk.StringVar()
t2 = tk.Entry(root, textvariable=var2).grid(row=ctr+1,column=2)
result = tk.StringVar()
result.set('label ' +str(ctr+1))
l = tk.Label(root, textvariable=result).grid(row=ctr+1,column=3)
lstentry.append(var1)
lstentry.append(var2)
lstlabel.append(l)
N = 3 # number of decimals that you want
def set_label(name, index, mode):
if var1.get() == '' or var2.get() == '':
pass
else:
res = float(var1.get()) * float(var2.get())
result.set('{number:.{digits}f}'.format(number=res, digits=N))
var1.trace('w', set_label)
var2.trace('w', set_label)
root.mainloop()
輸出

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超7個(gè)贊
將行創(chuàng)建邏輯與功能分開(kāi)add_row(row_number):
import tkinter as tk
root = tk.Tk()
root.geometry('850x450')
def add_row(row_number):
var1 = tk.StringVar()
t1 = tk.Entry(root, textvariable=var1).grid(row=row_number,column=1)
var2 = tk.StringVar()
t2 = tk.Entry(root, textvariable=var2).grid(row=row_number,column=2)
result = tk.StringVar()
l = tk.Label(root, textvariable=result).grid(row=row_number,column=3)
N = 3 # number of decimals that you want
def set_label(name, index, mode):
if var1.get() == '' or var2.get() == '':
pass
else:
res = float(var1.get()) * float(var2.get())
result.set('{number:.{digits}f}'.format(number=res, digits=N))
var1.trace('w', set_label)
var2.trace('w', set_label)
NUMBER_OF_ROWS = 10
for row_number in range(1, NUMBER_OF_ROWS+1):
add_row(row_number)
root.mainloop()
添加回答
舉報(bào)