如何在 tkinter 中添加第二行?

我需要使用计算函数将第二行添加到与第一行相同的位置。这段代码该怎么做


import tkinter as tk


root = tk.Tk()

root.geometry('850x450')


var1 = tk.StringVar()

t1 = tk.Entry(root, textvariable=var1).grid(row=1,column=1)

var2 = tk.StringVar()

t2 = tk.Entry(root, textvariable=var2).grid(row=1,column=2)

result = tk.StringVar()

l = tk.Label(root, textvariable=result).grid(row=1,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)


root.mainloop()

提前致谢...


Helenr
浏览 121回答 2
2回答

墨色风雨

如果要创建多行小部件,可以创建一个数组来存储小部件引用,并使用循环在网格中创建小部件。import tkinter as tkroot = tk.Tk()root.geometry('850x450')lstentry = []  # all entrieslstlabel = []  # all labelsfor 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 wantdef 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()输出

慕姐4208626

将行创建逻辑与功能分开add_row(row_number):import tkinter as tkroot = 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 = 10for row_number in range(1, NUMBER_OF_ROWS+1):    add_row(row_number)root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python