首页 > 解决方案 > 如何在 tkinter 中添加多个条目?

问题描述

我对 Tkinter 非常陌生。我一直在尝试创建一些基本上计算输入标记平均值的东西。我试图让用户选择主题数量,并相应地创建那么多条目。

from tkinter import *
root = Tk()
x, y, d = 0, 0, {}
for i in range(1, int(input('Enter no of subjects')) + 1):
    sub1 = Entry(root, width=15, borderwidth=5)
    sub1.grid(row=x, column=y)
    max1 = Entry(root, width=15, borderwidth=5)
    max1.grid(row=x, column=y+2)
    sub1label = Label(root, text='Marks attained', bg='grey', fg='white')
    sub1label.grid(row=x, column=y+1)
    max_sub1label = Label(root, text='Max Marks', bg='grey', fg='white')
    max_sub1label.grid(row=x, column=y+3)
    x += 1

root.mainloop()

有没有办法存储每次输入的数据以计算获取的百分比?或者我可以使用另一种方法吗?

标签: python-3.xtkinter

解决方案


您可以将值存储在列表中,然后稍后使用所需的值对列表进行索引并获取所需的项目。这是您更正的代码:

from tkinter import *

root = Tk()

def show():
    for i in range(tot_sub): # Loop through the number of subjects
        attained = attained_marks[i].get() # Get the indexed item from the list and use get()
        max_mark = max_marks[i].get()
        print(f'Attained marks: {attained}, Max marks: {max_mark}') # Print the values out

attained_marks = [] # Empty list to populate later
max_marks = [] # Empty list to populate later
tot_sub = int(input('Enter no. of subjects: ')) # Number of subjects
for i in range(tot_sub):
    sub1 = Entry(root, width=15, borderwidth=5)
    sub1.grid(row=i, column=0)
    attained_marks.append(sub1) # Append each entry to the list

    max1 = Entry(root, width=15, borderwidth=5)
    max1.grid(row=i, column=2)
    max_marks.append(sub1) # Append each entry to the list
    
    sub1label = Label(root, text='Marks attained', bg='grey', fg='white')
    sub1label.grid(row=i, column=1, padx=5)
    
    max_sub1label = Label(root, text='Max Marks', bg='grey', fg='white')
    max_sub1label.grid(row=i, column=3, padx=5)

root.bind('<Return>',lambda e: show()) # For demonstration of getting all the data

root.mainloop()

我还稍微更改了循环,因为您不需要初始化x,y,d等等,因为它可以从循环本身内部轻松实现。我还扩展了代码,以便您轻松理解。另外,我不建议将input()其用于终端,Entry而是使用 an 。

或者:您也可以使用 adict并避免使用 2 个列表,字典类似于{'Alternative Marks':[att1,att2,...],'Maximum Mark':[max1,max2,...]},但这会使循环和索引变得更冗长。


推荐阅读