Skip to content

[Bug]: plt.show(block=True) when a wx.App is already running #23072

@Yves33

Description

@Yves33

Bug summary

When trying to use pyplot interface from wx.App, pyplot.show() does not block and does not start an event loop

Code for reproduction

#!/usr/bin/env python
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('WXAgg')
import numpy as np
import wx

class TestFrame(wx.Frame):
    def __init__(self, parent, title):
        super(TestFrame, self).__init__(parent, title=title,size=(350, 250))
        self.sz=wx.BoxSizer()
        self.button=wx.Button(self,-1,"click")
        self.button.Bind(wx.EVT_BUTTON, self.onClick)   
        self.sz.Add(self.button,wx.EXPAND)
        self.SetSizer(self.sz)
        
    def onClick(self,evt):
        plt.plot(np.arange(0,6.28,0.1),np.sin(np.arange(0,6.28,0.1)))
        plt.show(block=True)
        ## as wx.App mainloop is running, matplotlib won't create an event loop. 
        ## we therefore need to manually create one!
        #plt.gcf().canvas.start_event_loop() #!magick line
        print("This shouldn't get printed before the closing the pyplot window!")

def main():
    app = wx.App()
    tf = TestFrame(None, title='Test app')
    tf.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

Actual outcome

With the above code, the line

print("This shouldn't get printed before the closing the pyplot window!")

gets executed even though the pyplot window is not closed.

Expected outcome

The line should not be executed before the pyplot window is closed

Additional information

In backend_wx.py, mainloop() is testing for wx.App.IsMainloopRunning(), which is True, and does not go any further.
Not a fix, but calling

plt.gcf().canvas.start_event_loop()

immediately after plt.show()
restores the blocking behaviour. Wondering if it is reliable or if this trick may break in a near future?

Operating system

Windows10

Matplotlib Version

3.4.3

Matplotlib Backend

WX; WXAgg

Python version

3.8.8

Jupyter version

not applicable

Installation

conda

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions