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

如何从JSON读取的字典列表中删除toolsOut为空列表的条目并格式化输出到GUI

解决方案

修改思路

  • 移除原代码中pprint格式化+多次字符串替换的逻辑,该处理方式容错率极低,格式易出错
  • 遍历用户数据时新增过滤逻辑,直接跳过toolsOut为空列表的条目
  • 按照需求的格式逐行构造输出内容,拼接后传入Label控件即可

完整修改后代码

## importing libraries
import json
from tkinter import *
from tkinter import ttk
from functools import partial

mainWin = Tk()
mainWin.geometry('400x480')
mainWin.title('Select Tooling')

with open('Inventory.json','r+') as json_file:
    data=json.load(json_file)
    credData = data['Credentials']
    output_lines = []
    for user in credData:
        # 过滤toolsOut为空的条目
        if not user['toolsOut']:
            continue
        # 格式化工具列表为带单引号、逗号分隔的字符串
        formatted_tools = ", ".join([f"'{tool}'" for tool in user['toolsOut']])
        output_lines.append(f"{user['realName']}: {formatted_tools}")
    # 所有行用换行符拼接,设置Label左对齐更易读
    text = Label(mainWin, text="\n".join(output_lines), justify=LEFT)
    text.pack()

quitButton = Button(mainWin,text="Log Out",command=lambda:mainWin.destroy())
quitButton.pack()

mainWin.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:24:05