首页 > 解决方案 > pySimpleGUI 和 Python

问题描述

我想要一些帮助。

我正在训练这段代码:

    import PySimpleGUI as sg

    category = ['Smartphone', 'Battery', 'Charger']
    brand = ['Iphone', 'Motorola', 'LG']
    color = ['White', 'Green', 'Black']
    size_font = 20

    layout = [[sg.Text('Code', font=size_font), sg.Input(key='-COD-', font=size_font, size=(20, 1))],
              [sg.Text('Un', font=size_font), sg.InputText(key='-UN-', font=size_font, size=(10, 1))],
              [sg.Text('Name', font=size_font), sg.Input(key='-NAME-', size=(30, 1))],
              [sg.Text('Category', font=size_font), sg.Combo(category, font=size_font, key='-CATEG-', size=(30, 1))],
              [sg.Text('Brand', font=size_font), sg.Combo(marca, font=size_font, key='-BRAND-')],
              [sg.Text('Color', font=size_font), sg.Combo(color, font=size_font, key='-COL-')],
              [sg.Text('')],
              [sg.Button('Insert', font=size_font), sg.Button('Cancel', font=size_font)]]

    window = sg.Window('Product Registration', layout, size=(700, 300))

    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Cancel'):
            break
        if event == 'Insert':
            window['-NAME-'].update(window['-CATEG-'])


    window.close()

我希望在 Combo 列表中选择的值(其键为 ='-CATEG-' )填写在 key = '-NAME-' 中。但是对象正在返回而不是选择的值,例如:<PySimpleGUI.PySimpleGUI.Combo object at 0x7fd8bf982a60>。还有一件事:您可以连接键:'-CATEG-' + '-BRAND-' + '-COLOR-' 将此连接放置在 key = '- NAME-' 中吗?示例:在“类别”组合中,选择了智能手机选项;在“品牌、摩托罗拉”和“颜色”中,黑色。因此,“名称”字段应为:Smartphone Motorola Black。

此外,创建变量来定义一些参数是一个好习惯,就像对变量“size_font”所做的那样?我是这么想的,因为我相信维护会更容易。

标签: pythonpysimplegui

解决方案


  1. 获取选定的值values[key],而不是window[key]
window['-NAME-'].update(values['-CATEG-'])
  1. 使用方法str.join连接所有字符串
text = ' '.join([values['-CATEG-'], values['-BRAND-'], values['-COLOR-']])
window['-NAME-'].update(text)
  1. 在使用元素之前设置默认选项
size_font = ("Courier New", 20)
sg.set_options(font=size_font)

推荐阅读