python-3.x - 如何在 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()
有没有办法存储每次输入的数据以计算获取的百分比?或者我可以使用另一种方法吗?
解决方案
您可以将值存储在列表中,然后稍后使用所需的值对列表进行索引并获取所需的项目。这是您更正的代码:
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,...]}
,但这会使循环和索引变得更冗长。
推荐阅读
- ios - 如何丢弃 Swift 中当前正在运行的函数?
- node.js - MongoDB:如何按值查找文档?
- python - 端点中的 FastAPI 冲突路径参数 - 良好做法?
- css - 如何调整移动标志的大小
- android - 如何使用 LinearLayout 在中心添加 CardView
- javascript - 将值 {null} 转换为类型“System.Int32”时出错 400 错误
- azure-logic-apps - 在逻辑应用工作流中另存为 .PARQUET 文件
- react-native - 如何从导航器中的屏幕转到另一个导航器中的屏幕?
- javascript - 受信任的浏览器事件可以防御哪些威胁?
- python - 是否有可能在 Python 中获得超过 1 个字符串中的字符频率?