我想使用 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()]]
Run Code Online (Sandbox Code Playgroud)
我想这就是你要找的?
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)
Run Code Online (Sandbox Code Playgroud)
它产生这个窗口:
有多种“构建”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
Run Code Online (Sandbox Code Playgroud)
这个也是一次构建一行,然后将它们添加在一起,但它是在单个语句中而不是 4 中完成的。
# Build layout
layout = [[sg.Text('My layout')]] + \
[[sg.Radio(text, 1) for text in radio_choices]] + \
[[sg.Button('Read')]]
Run Code Online (Sandbox Code Playgroud)
如果你想每行添加一个这些按钮,那么也有几种方法可以做到这一点。如果您使用的是 Python 3.6,那么这将起作用:
layout = [
[sg.Text('My layout')],
*[[sg.Radio(text, 1),] for text in radio_choices],
[sg.Button('Read')]
]
Run Code Online (Sandbox Code Playgroud)
“构建布局”技术适用于上述 * 运算符无效的系统。
radio_choices = ['a', 'b', 'c']
radio = [[sg.Radio(text, 1),] for text in radio_choices]
layout = [[sg.Text('My layout')]] + radio + [[sg.OK()]]
Run Code Online (Sandbox Code Playgroud)
当结合窗口代码和事件循环时,这两种变体将产生一个如下所示的窗口:

| 归档时间: |
|
| 查看次数: |
3482 次 |
| 最近记录: |