Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

json - Why is my python function printing out {}Main and not just Main?

I am using a function to grab my data from a json file and print it to a tkinter combo box, for some reason the first word always has {} in front of it. My json data doesn't have it so why does it appear in my output?

    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 is also preset to have nothing in it so the values container code looks like this: profiles_select = ttk.Combobox(new_task_frame1, width=10, values=[])

Here is the json sample data:

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

This is what i expect to show up in my tkinter combo box :

Main
Test

This is what actually outputs

{}Main
Test
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Question: Why is my python function printing out '{}Main' and not just 'Main'?

  • Initalizing profiles_select['values']
    profiles_select = ttk.Combobox(new_task_frame1, width=10, values=[])
    
    This results, widget internal, to: '', tcl uses: '{}'

  • Adding options
    profiles_select['values'] = (profiles_select['values'], add_profile)
    
    You take the internal value ''and a new option 'Main', which results in ('', 'Main').

  • How tkinter shows the Listbox options

    Your two options:

    {}Main  
    Test
    

    More than two options:

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

Conclusion, don't update options using:
profiles_select['values'] = (profiles_select['values'], add_profile)


Solution: Create your sequence first and assign it in whole once.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...