You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter中获取数量可变的Entry组件的值?

解决方法

问题出在你循环创建Entry组件时,每次都会覆盖entry变量,导致最终只能访问到最后一个Entry实例。要获取所有Entry的值,你需要把每个Entry组件和对应的价格关联存储起来,比如用字典来保存。

以下是修改后的代码:

import sys
import tkinter as tk
from tkinter import ttk

def share_cost_basis(fund, pool, price):
    # 创建字典存储价格与对应Entry的映射
    entry_dict = {}

    def get_px(*args):
        # 生成结果字典:价格 -> 计算后的成本基数
        result = {}
        for p, entry in entry_dict.items():
            try:
                share_num = float(entry.get())
                cost_basis = float(p) * share_num
                result[p] = cost_basis
            except ValueError:
                # 处理输入非数字的情况,可选
                print(f"输入错误:价格{p}对应的份额不是有效数字")
                return
        print("计算结果:", result)
        form.destroy()
        sys.exit(0)

    form = tk.Tk()
    form.update_idletasks()
    width = 400
    height = 450
    x = int((form.winfo_screenwidth() / 2) - (width / 2))
    y = int((form.winfo_screenheight() / 2) - (height / 2))
    form.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    form.title('Cost Basis per Share Entry')
    form_label = ttk.Label(form, text=f'For the fund {pool} {fund}, please enter the number of\n'
                                      f' shares that were purchased at each price.\n')
    form_label.grid(column=1, row=1, columnspan=4, sticky='E,W', pady=(20, 0), padx=(10, 0))

    for idx, p in enumerate(price):
        row_num = idx + 2
        label_frame = ttk.LabelFrame(form, borderwidth=10, relief='sunken')
        label_frame.grid(row=row_num, column=1, pady=5, sticky='e', columnspan=2)
        label = ttk.Label(label_frame, text=p)
        label.grid(row=row_num, column=1, columnspan=2)
        entry = ttk.Entry(form)
        entry.grid(row=row_num, column=3)
        # 将当前Entry存入字典,键为价格p
        entry_dict[p] = entry

    ok_button = ttk.Button(form, text='OK', command=get_px)
    ok_button.grid(row=row_num+2, column=2)
    form.mainloop()

share_cost_basis('Test Fund', 'Test Pool', ['1.25', '2.50', '3.75', '5.00'])

关键修改点:

  • 新增entry_dict字典,用于存储每个价格对应的Entry组件,避免变量被覆盖
  • 循环中使用enumerate获取索引来计算行号,比price.index(p)更高效(尤其是当价格列表有重复值时)
  • 在get_px函数中遍历entry_dict,逐个获取Entry的输入值并计算,最终生成你需要的字典格式结果
  • 加入了简单的异常处理,防止用户输入非数字导致程序崩溃

内容的提问来源于stack exchange,提问作者AJames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:40:15