pysimplegui - 如何使用 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()]]
解决方案
我想这就是你要找的吗?
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()]]
推荐阅读
- c++ - 如何对类声明进行字符串化并定义它?
- for-loop - 如果href在selenium python中只有https,如何请求
- dom - 如何使用 Svelte 将 CSS 属性绑定到表格单元格
- app-store - Xcode 13.0 在 macOS BigSur 11.6 上安装时卡住
- php - Moodle - 高级论坛防止在页面刷新时将所有标记为已读
- sharepoint - Microsoft Power Automate 检查文件名格式标准适用
- django - Django 模板 - 如何自动增加整数?
- laravel - Eloquent - 返回为 0000-00-00 的可空日期列
- nuxt.js - 使用 Nuxt 和 Vuex 自动完成搜索?
- javascript - Nodejs异步函数未按顺序运行