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

如何将Tkinter中Entry组件的输入内容存入列表并解决空值问题

问题根源

你代码的核心问题是执行时机错误:在new_entry函数中刚创建完Entry控件、还没等用户输入内容时,就立刻调用了get()方法读取值,此时输入框默认是空的,所以存入列表的永远是空字符串。
同时你的代码存在命名冲突问题:函数名new_entry和内部创建的Entry控件变量名重名,属于不规范写法,容易引发后续逻辑错误。

修正方案

推荐优先使用「存储Entry控件对象,需要时再读取值」的方案,该方案可以随时获取输入框的最新内容,适配排序等动态需求,修改逻辑如下:

  1. 将Entry控件对象直接存入列表,而非创建时就读取值
  2. 在点击排序按钮等需要使用输入内容的场景下,再遍历列表批量读取最新值
  3. 修正变量命名冲突问题

完整可运行修改后代码

from tkinter import *
root = Tk()
root.title('sorter')

number = 0
# 现在列表存储Entry控件对象,而非字符串
entry_list = []

def new_entry():
    global number
    number += 1
    # 序号标签
    number_label = Label(root, text=number, width=20)
    number_label.grid(row=number, column=0)
    # 输入框,修正命名冲突
    entry_field = Entry(root, borderwidth=3, width=100)
    entry_field.grid(row=number, column=1, columnspan=4)
    # 存入控件对象
    entry_list.append(entry_field)

# 示例:按序号排序的回调函数,其他排序按钮逻辑可以参考这里实现
def sort_by_number():
    # 需要用的时候再读取所有输入框的最新值
    all_content = [entry.get() for entry in entry_list]
    # 这里写你的排序逻辑,现在打印测试
    print("当前所有输入内容:", all_content)

# 绑定按钮回调
number_for_list = Button(root, text='Sort by number', borderwidth=3, width=20, command=sort_by_number)
button_for_1_name = Button(root, text='Sort by first name', borderwidth=3, width=20)
button_for_2_name = Button(root, text='Sort by second name', borderwidth=3, width=20)
button_for_3_name = Button(root, text='Sort by third name', borderwidth=3, width=20)
new_entry_button = Button(root, text='New entry', borderwidth=3, command=new_entry, width=20)

# 按钮位置
number_for_list.grid(row=0, column=0)
button_for_1_name.grid(row=0, column=1)
button_for_2_name.grid(row=0, column=2)
button_for_3_name.grid(row=0, column=3)
new_entry_button.grid(row=0, column=4)

root.mainloop()

验证方法

运行代码后点击几次「New entry」生成多个输入框,在输入框中填写内容后点击「Sort by number」按钮,控制台就会输出所有输入框的真实内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:06:07