【问题标题】:Create list of strings for gui from object in python从python中的对象创建gui的字符串列表
【发布时间】:2021-10-23 16:30:57
【问题描述】:

我正在使用 PySimpleGUI,我想为下拉菜单创建动态选项。

我的代码:

#in file gui.py
import PySimpleGUI as psg

layout = [[psg.Text('Choose category:', size=(20, 1), font='Lucida', justification='left')],
          [psg.Combo([prep_data.prepare_dropdown_categories()],
                     default_value='All crimes', key='all')],
          [psg.Button('SAVE', font=('Lucida', 12)), psg.Button('CANCEL', font=('Lucida', 12))]]

#in file prep_data.py
def prepare_dropdown_categories():
    categories = []
    fetched_categories = fetch_categories() #this fetches categories from an api, returns json.loads(data)
    for category in fetched_categories:
        categories.append(category['name'])

    return categories

我要的具体数据(api):https://data.police.uk/api/crime-categories

我的结果是一个下拉菜单,其中一个选项存储所有“名称”字符串:

{name0}{name1}{name2}name3{name4}

是的,并非所有人都在他们周围有花括号...... 我希望有人知道如何正确地做到这一点。

感谢您的帮助。

【问题讨论】:

  • 从 API 中查看至少足够的数据以重现问题可能很有用。原来如此……?
  • 我添加了链接@MattMorgan
  • 有什么问题?
  • 问题是我需要这样的列表 ["name0", "name1", "name2"] 但它给了我这个 [{name0}name1{name2}] @balderman(至少我认为这就是问题所在)
  • 你能做到print(fetched_categories) 吗?

标签: python json api


【解决方案1】:

名字没问题 - 见下文。确保获得相同的列表。

import requests

r = requests.get('https://data.police.uk/api/crime-categories')
if r.status_code == 200:
  print([x['name'] for x in r.json()]) 

输出

['All crime', 'Anti-social behaviour', 'Bicycle theft', 'Burglary', 'Criminal damage and arson', 'Drugs', 'Other theft', 'Possession of weapons', 'Public order', 'Robbery', 'Shoplifting', 'Theft from the person', 'Vehicle crime', 'Violence and sexual offences', 'Other crime']

【讨论】:

  • 太好了! :) 加上 'prep_data.prepare_dropdown_categories()' 周围没有括号谢谢!
猜你喜欢
  • 2019-02-21
  • 2015-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2019-01-15
  • 1970-01-01
  • 1970-01-01
  • 2010-10-15
相关资源
最近更新 更多