实现将写重复的控件代码使用循环进行实现
示例一
实现效果
- 未使用循环前实现代码如下:
import PySimpleGUI as sg
layout = [
[sg.Text('1. '), sg.In(key=1)],
[sg.Text('2. '), sg.In(key=2)],
[sg.Text('3. '), sg.In(key=3)],
[sg.Text('4. '), sg.In(key=4)],
[sg.Text('5. '), sg.In(key=5)],
[sg.Button('Save'), sg.Button('Exit')]
]
window = sg.Window('To Do List Example', layout)
event, values = window.read()
- 使用循环后实现代码如下
import PySimpleGUI as sg
layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)]
layout += [[sg.Button('Save'), sg.Button('Exit')]]
window = sg.Window('To Do List Example', layout)
event, values = window.read()
或者
import PySimpleGUI as sg
layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]]
window = sg.Window('To Do List Example', layout)
event, values = window.read()
- 再次对其进行封装
import PySimpleGUI as sg
def ToDoItem(num):
return [sg.Text(f'{num}. '), sg.CBox(''), sg.In()]
layout = [ToDoItem(x) for x in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]]
window = sg.Window('To Do List Example', layout)
event, values = window.read()
示例二
实现效果
import PySimpleGUI as sg
sg.theme('Dark Brown 1')
headings = ['HEADER 1', 'HEADER 2', 'HEADER 3','HEADER 4']
header = [[sg.Text(' ')] + [sg.Text(h, size=(14,1)) for h in headings]]
#for row in range(10) 外层循环,循环行
#for col in range(4) 内层循环,循环列
input_rows = [[sg.Input(size=(15,1), pad=(0,0)) for col in range(4)] for row in range(10)]
layout = header + input_rows
window = sg.Window('Table Simulation', layout, font='Courier 12')
event, values = window.read()