pysimplegui - Main Window Not Responding While Second Window is Open

  • 1 year ago
Comment

1 / 1

If you're using PySimpleGUI and the main window is not responding while a second window is open, it's likely that your program is running in a single thread and the event loop is blocked.

PySimpleGUI is based on the Tkinter library, which is not thread-safe. Therefore, running your PySimpleGUI program in a single thread is recommended. However, if you're performing long-running tasks in the main event loop or in callbacks, this can block the event loop and cause the GUI to become unresponsive.

To avoid this issue, you can use the non_blocking parameter when creating your second window. This will allow your program to continue running the event loop for the main window while the second window is open.

Here's an example code snippet that demonstrates how to use the non_blocking parameter:

python
import PySimpleGUI as sg

# Define the layout for the main window
layout = [[sg.Text("Main Window")], [sg.Button("Open Second Window")]]

# Create the main window
window = sg.Window("Main Window", layout)

# Event loop for the main window
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == "Open Second Window":
# Define the layout for the second window
layout = [[sg.Text("Second Window")], [sg.Button("Close")]]

# Create the second window with non-blocking
window2 = sg.Window("Second Window", layout, non_blocking=True)

# Event loop for the second window
while True:
event, values = window2.read()
if event == sg.WIN_CLOSED or event == "Close":
window2.close()
break

# Close the main window
window.close()

In this example, the main window has a button that opens a second window when clicked. The second window is created with the non_blocking=True parameter, which allows the event loop for the main window to continue running while the second window is open.

Note that the non_blocking parameter is only available in PySimpleGUI version 4.40 or later. If you're using an earlier version of PySimpleGUI, you may need to use threading or multiprocessing to run your program in multiple threads or processes. However, this can be more complex and may introduce new issues, so using non_blocking is the recommended approach.