2 回答
TA贡献1853条经验 获得超6个赞
如果要创建多行小部件,可以创建一个数组来存储小部件引用,并使用循环在网格中创建小部件。
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贡献1852条经验 获得超7个赞
将行创建逻辑与功能分开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()
添加回答
举报