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

Tkinter Entry从字典选值填充时始终取最后一条记录问题求解

问题根因

你遇到的问题是Python闭包的延迟绑定特性导致的:循环里定义的select函数在被调用时才会去取dicts变量的值,此时循环已经执行完毕,dicts永远指向字典列表的最后一条记录,所以所有按钮点击都填充最后一行数据。

修复方案

只需要修改display函数的逻辑即可,修改后的代码如下:

def display() :
    # 先清空之前渲染的旧记录,避免重复展示
    for widget in frm_details.winfo_children():
        widget.destroy()
    # 重新渲染表头
    lbl_record = tk.Label(master=frm_details , height=1, width=30, bg = 'white', relief=tk.GROOVE, text='user',justify="right")
    lbl_record.grid(row=0, column=0, padx=5)

    lbl_result["text"] = show()
    record = show()
    for n, dicts in enumerate(record):
        position = n
        user = dicts['name']
        lbl_record = tk.Label(master=frm_details, height=1, width=40, bg = 'white', relief=tk.GROOVE, text=user,justify="right")
        lbl_record.grid(row=1+position, column=0, padx=5)
        # 用默认参数绑定当前循环的dicts值,解决延迟绑定问题
        def select(current_dict=dicts):
            Clear()
            ent_user.insert(tk.END,current_dict['name'])
            ent_pw.insert(tk.END,current_dict['password'])
            ent_city.insert(tk.END,current_dict['city'])
            ent_code.insert(tk.END,current_dict['code']) 
        btn_recSelect = tk.Button(master=frm_details ,width=5, bg = 'white', text='select',command=select)
        btn_recSelect.grid(row=1+position, column=1, padx=2,sticky=tk.W)
    return True

另外你原代码里绑定了ent_code.bind("<Button-1>", lambda event: clear_entry(ent_code)),但缺少clear_entry函数的定义,补上这段就能正常运行:

def clear_entry(entry):
    entry.delete(0, END)

额外优化说明

  • 新增了每次调用display时先清空旧记录的逻辑,避免多次点击Display按钮重复叠加展示记录
  • 删掉了原来多余的for v, k in dicts.items()循环,这个循环没有实际作用,完全可以省略

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:45:06