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

如何将Tkinter动态生成的Entry输入框内容保存为字典格式

Tkinter输入值转指定字典结构输出修改方案

核心修改点为调整showEntries方法的取值逻辑,将原嵌套列表结构替换为你需要的字典结构即可,无需改动其他业务逻辑,完整修改后代码如下:

from tkinter import *
# 如需输出严格JSON格式字符串可导入json模块
# import json

class sample:
    def __init__(self, root):
        self.root = root
        self.root.geometry("500x500")
        self.all_entries = list()

        showButton = Button(root, text='Show all text',command= self.showEntries)
        showButton.pack()

        addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=self.addBox)
        addboxButton.pack()

    def addBox(self):
        frame = Frame(root)
        frame.pack()

        self.ent1 = Entry(frame)
        self.ent1.grid(row=1, column=0)

        self.ent2 = Entry(frame)
        self.ent2.grid(row=1, column=1)

        self.all_entries.append([self.ent1,self.ent2])

    def showEntries(self):
        # 修改此处逻辑生成指定结构的字典列表
        values = [{"ent1": ent1.get(), "ent2": ent2.get()} for ent1, ent2 in self.all_entries]
        print(values)
        # 如需输出严格双引号的JSON格式,替换上面的print为下面的代码即可
        # print(json.dumps(values))

root = Tk()
obj = sample(root)
root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:27:03