Ask Your Question
4

How can PySimpleGUI be used to create frames that have dynamic buttons?

asked 2021-06-20 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-12-20 11:00:00 +0000

huitzilopochtli gravatar image

There are a few steps to create frames with dynamic buttons using PySimpleGUI:

  1. Define the layout of your main window, including any frames that you want to display. You can use placeholders for the buttons at this point.
import PySimpleGUI as sg

layout = [
  [sg.Frame(title='Frame 1', layout=[[sg.Button('Button 1'),
                                       sg.Button('Button 2'),
                                       sg.Button('Button 3'),
                                       sg.Button('Button 4')],
                                      [sg.Button('Add Button')]])],
  [sg.Button('Exit')]
]

window = sg.Window('Dynamic Buttons', layout)
  1. Define a function that can add a new button to the frame when the "Add Button" button is clicked. This function should update the layout of the frame to include the new button, and then update the window layout to reflect the changes.
def add_button(frame):
  num_buttons = len(frame.Children[0])
  new_button = sg.Button(f'Button {num_buttons+1}')
  frame.Children[0] += [new_button]
  frame.Update(frame.TKCanvas, frame.Locat)
  window.Update()
  1. Set up an event loop to handle user input. In the event loop, you can handle button clicks and call the add_button function when the "Add Button" button is clicked.
while True:
  event, values = window.read()
  if event == sg.WIN_CLOSED or event == 'Exit':
    break
  elif event == 'Add Button':
    add_button(window['Frame 1'])

With these steps, you should be able to create a PySimpleGUI interface that has frames with dynamic buttons that can be added at runtime.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-20 11:00:00 +0000

Seen: 1 times

Last updated: Dec 20 '22