如何以编程方式关闭matplotlib窗口?

时间:2019-05-05 15:50:29

标签: python matplotlib

我实现了一个ROI选择功能,该功能会生成一个matplolib窗口。选择完成后,我想关闭此功能并继续执行我的其余代码。选择结束时,其余代码运行良好,但窗口从未关闭。

我尝试了三种关闭窗口的方法:

self.fm = plt.get_current_fig_manager()
self.fm.destroy()
plt.show(block=False)
class RectangleSelection(object):
    def __init__(self, img):
        self.rectangle = None
        self.img = img
        self.done = False

        #Setup the figure
        self.fig, self.ax = plt.subplots()
        self.fm = plt.get_current_fig_manager()
        plt.ion
        plt.imshow(self.img, cmap='gray')

        self.RS = RectangleSelector(self.ax, self.onselect,
                                       drawtype='box', useblit=True,
                                       button=[1, 3],  
                                       minspanx=5, minspany=5,
                                       spancoords='pixels',
                                       interactive=True)

        plt.connect('key_press_event', self.toggle_selector)
        plt.show()

    def onselect(self, e_click, e_release):
        # [...] do stuff

    def toggle_selector(self, event):
        if event.key in ['Q', 'q'] and self.RS.active:
            self.RS.set_active(False)
            self.done = True

    def close(self):
        logging.debug("Closing selection window")
        plt.show(block=False)
        plt.close('all')
        self.fm.destroy()

但它们都没有关闭窗口。

这是选择器类的有效示例:

selector = RectangleSelection(img)
while not selector.done:
    pass
crop_box = selector.rectangle
logging.debug("Got crop_box %s", str(crop_box))
selector.close() # I want the window to close at this point
plt.pause(0.5)

long_process(crop_box)
# The window eventually closes when the process completely finishes.

和调用函数

selector.close()

import matplotlib.pyplot as plt plt.ion() plt.plot([1.6, 2.7]) # This shows the plot in a window plt.title("Test Title") # This works showing the link between code and plot is there plt.clf() # This works too, clearing the figure plt.close() # This makes the plot window unresponsive but does not close it. 被调用(如一条记录消息所示),但不会导致窗口关闭。

在ipython提示符中一个简短的工作示例如下:

The Pseudocode: 
A[n]
Queue[n] // Same size as the size of the array
i =0
while i < (n-1)
Rear = 0
Max = A[i]
Queue[Rear] = i
j= i+1
while j<(n)
if Max < A[j]
Max =  A[j]
Rear = -1
If Max = A[j]
Rear = Rear + 1
Queue[Rear] = j
//Perform the swapping of values
Front=  0
while (Front <= Rear)
Temp =A[Queue[Front]]
A[Queue[Front]] = A[i]
A[i] = Temp
i = i + 1
Front = Front + 1

1 个答案:

答案 0 :(得分:0)

感谢您的评论。看来这可能是Tkinter后端中的错误。切换到Qt4Agg后端会产生预期的行为,其中plt.close()将按预期方式关闭窗口。