首页 > 解决方案 > 如何使用 PySimpleGui 从列表中创建单选按钮?

问题描述

我想使用 PySimpleGui 从列表中动态创建单选按钮,但我在布局代码中插入循环的努力正在捕获语法错误。这可以用 API 完成还是我需要用 tkinter 来完成?我的列表是通过网络驱动器的目标文件搜索生成的。

我尝试连接“布局”,将单选按钮部分放在 for 循环中。还尝试在 [sg.Radio()] 声明本身中插入一个 for 循环。两者都不起作用。

import PySimpleGUI as sg

xList = ['a', 'b', ... 'zz']

layout = [[sg.Text('Select a thingy')],
          [sg.Radio(<for thingy in xList: 'thingy', thingy>)],
                   #^^^^^^ for loop is psuedo code
          [sg.OK(), sg.Cancel()]]

标签: pysimplegui

解决方案


我想这就是你要找的吗?

import PySimpleGUI as sg

radio_choices = ['a', 'b', 'c']
layout = [
            [sg.Text('My layout')],
            [sg.Radio(text, 1) for text in radio_choices],
            [sg.Button('Read')]
         ]

window = sg.Window('Radio Button Example', layout)

while True:             # Event Loop
    event, values = window.Read()
    if event is None:
        break
    print(event, values)

它产生这个窗口:

在此处输入图像描述

有多种“构建”layout变量的方法。以下是产生相同窗口的其他几个组合:

第一个一次构建一行,然后最后将它们加在一起

# Build Layout
top_part = [[sg.Text('My layout')]]
radio_buttons = [[sg.Radio(x,1) for x in radio_choices]]
read = [[sg.Button('Read')]]
layout = top_part + radio_buttons + read

这个也一次构建一行,然后将它们添加在一起,但它在单个语句中而不是 4 个语句中完成。

   # Build layout
    layout = [[sg.Text('My layout')]] + \
                [[sg.Radio(text, 1) for text in radio_choices]] + \
                [[sg.Button('Read')]]

如果您想每行添加一个按钮,那么也有几种方法可以做到这一点。如果您使用的是 Python 3.6,那么这将起作用:

layout = [
            [sg.Text('My layout')],
            *[[sg.Radio(text, 1),] for text in radio_choices],
            [sg.Button('Read')]
         ]

“构建布局”技术适用于上述 * 运算符无效的系统。

radio_choices = ['a', 'b', 'c']
radio = [[sg.Radio(text, 1),] for text in radio_choices]
layout = [[sg.Text('My layout')]] + radio + [[sg.OK()]]

当与窗口代码和事件循环结合时,这两种变化都会产生一个如下所示的窗口: 在此处输入图像描述


推荐阅读