【问题标题】:Why is my python function printing out {}Main and not just Main?为什么我的 python 函数打印出 {}Main 而不仅仅是 Main?
【发布时间】:2020-01-18 22:03:04
【问题描述】:

我正在使用一个函数从 json 文件中获取我的数据并将其打印到 tkinter 组合框,由于某种原因,第一个单词前面总是有 {}。我的 json 数据没有,为什么会出现在我的输出中?

    with open('profiles.txt', 'r') as file:
        profiles = json.load(file)
        for profile in profiles:
            add_profile = profile['profile_name']
            profiles_select['values'] = (profiles_select['values'], add_profile)

Values 也被预设为没有任何内容,因此 values 容器代码如下所示:profiles_select = ttk.Combobox(new_task_frame1, width=10, values=[])

这里是json示例数据:

[
    {
        "profile_name": "Main",
        "first_name": "Michael ",
    },
    {
        "profile_name": "Test",
        "first_name": "Michael ",
    }
]

这是我希望在我的 tkinter 组合框中显示的内容:

Main
Test

这是实际输出的内容

{}Main
Test

【问题讨论】:

  • 请提供minimal reproducible example。您尚未展示任何创建或将数据输入组合框的代码。
  • @BryanOakley 我展示了这两个... 第一个代码块中的profiles_select['values'] = (profiles_select['values'], add_profile) 显示我将值添加到组合框中。我还展示了 profiles_select = ttk.Combobox(new_task_frame1, width=10, values=[]) 的框的创建
  • 应该是profile_select['values'].append(add_profile)。
  • @acw1668 你不能直接附加它,它返回'str' object has no attribute 'append'
  • 然后把整个for循环改成profiles_select['values'] = tuple(x['profile_name'] for x in profiles).

标签: python json tkinter


【解决方案1】:

问题:为什么我的python函数打印出'{}Main'而不仅仅是'Main'?

  • 正在初始化profiles_select['values']
    profiles_select = ttk.Combobox(new_task_frame1, width=10, values=[])
    
    这个结果,小部件内部,到:'',tcl 使用:'{}'

  • 添加选项
    profiles_select['values'] = (profiles_select['values'], add_profile)
    
    您采用内部值 '' 和一个新选项 'Main',结果为 ('', 'Main')。

  • tkinter 如何显示Listbox 选项

    您的两个选项:

    {}Main  
    Test
    

    多于两个选项:

    profiles_select['values'] = ('{{{} Main} Test} Test2', 'Test3')
    
    {{{} Main} Test} Test2
    Test3
    

结论,不要使用更新选项:
profiles_select['values'] = (profiles_select['values'], add_profile)


解决方案:首先创建您的序列,然后将其全部分配一次。

with open('profiles.txt', 'r') as file:
    profiles = json.load(file)

    options = []
    for profile in profiles:
        options.append(profile['profile_name'])

    profiles_select['values'] = options

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-11
    • 2014-12-18
    • 2010-12-13
    • 1970-01-01
    • 2011-09-24
    • 2020-11-15
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多