python matplotlib如何使用类打开图像

python matplotlib如何使用类打开图像,python,image,class,matplotlib,Python,Image,Class,Matplotlib,我对matplotlib非常熟悉,我尝试编写一个类来通过matplotlib打开和关闭图像,下面是代码: import matplotlib matplotlib.use("TkAgg") import matplotlib.pyplot as plt class ptlShow(): def __init__(self, file, pos): plt.rcParams['toolbar'] = 'None' fig, ax = plt.subplo

我对matplotlib非常熟悉,我尝试编写一个类来通过matplotlib打开和关闭图像,下面是代码:

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

class ptlShow():
    def __init__(self, file, pos):
        plt.rcParams['toolbar'] = 'None'

        fig, ax = plt.subplots(figsize=(1, 1.4))
        fig.subplots_adjust(0, 0, 1, 1)

        ax.axis("off")

        im = plt.imread(file)
        ax.imshow(im)


        fig.canvas.manager.window.overrideredirect(1)
        plt.get_current_fig_manager().window.wm_geometry(pos)#  
        plt.show()

    def close(self):
        plt.close




a = ptlShow('1.jpg', '+700+100')
b = ptlShow('2.jpg', '+500+100')

a.close()
b.close()
但最后我只有一个实例的形象和关闭不工作,我做错了!谢谢

plt.show()
意味着在脚本结束时只调用一次,因为它接管了事件循环。之后的代码在所有图形关闭之前不会执行

您可能希望通过单击图形来关闭该图形,以便可以将关闭方法注册到
按钮\u press\u事件
。请注意,
plt.close
只是一个函数,您可以调用它:
plt.close()

为了在一段时间t后关闭窗口,您可以使用
tkinter
s
.after
方法,
.after(t,func)


谢谢!好的,但是我怎样才能关闭“a”图像呢?通过点击它。当然,但在我的情况下,我需要通过代码来完成它!正如你所看到的,我和图像没有边界!也许我可以模拟按键???你可以显示它,然后关闭它,这基本上意味着你根本看不到它;但我猜这不是你的意思?我需要在没有用户交互的情况下通过代码显示和关闭图像!
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt


class ptlShow():
    def __init__(self, file, pos):
        plt.rcParams['toolbar'] = 'None'

        self.fig, ax = plt.subplots(figsize=(1, 1.4))
        self.fig.subplots_adjust(0, 0, 1, 1)

        ax.axis("off")

        im = plt.imread(file)
        ax.imshow(im)

        self.fig.canvas.manager.window.overrideredirect(1)
        self.fig.canvas.manager.window.wm_geometry(pos)# 
        self.fig.canvas.mpl_connect("button_press_event", self.close)

    def close(self, event=None):
        plt.close(self.fig)

a = ptlShow('1.jpg', '+700+100')
b = ptlShow('2.jpg', '+500+100')

plt.show()
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt


class ptlShow():
    def __init__(self, file, pos):
        plt.rcParams['toolbar'] = 'None'

        self.fig, ax = plt.subplots(figsize=(1, 1.4))
        self.fig.subplots_adjust(0, 0, 1, 1)

        ax.axis("off")

        im = plt.imread(file)
        ax.imshow(im)


        self.fig.canvas.manager.window.overrideredirect(1)
        self.fig.canvas.manager.window.wm_geometry(pos)# 
        self.fig.canvas.mpl_connect("button_press_event", self.close)
        self.fig.canvas.mpl_connect("draw_event", self.delayed_close)

    def delayed_close(self,event=None):
        self.fig.canvas.manager.window.after(1000, self.close)
    def close(self, event=None):
        plt.close(self.fig)

a = ptlShow('house.png', '+700+100')
b = ptlShow('house.png', '+500+100')

plt.show()