matplotlib PolygonSelector 在 tkinter 中调用时冻结

我正在使用 tkinter 和 matplotlib 编写脚本进行数据处理,代码的某些部分需要多边形选择器来选择感兴趣的区域。但是,PolygonSelector 无法检测光标的运动。


需要注意的是,这个问题是在matplotlib图形交互模式开启的情况下出现的。


简化代码和结果如下所示:


#!/usr/bin/env python3

import matplotlib

matplotlib.use("TkAgg")

import tkinter as tk

import matplotlib.pyplot as plt

from matplotlib.widgets import PolygonSelector


root = tk.Tk()


def draw():

    fig = plt.figure()

    ax = fig.add_subplot(111)

    plt.ion()    # interactive mode is on

    plt.show()


    def onselect(data_input):

        print(data_input)


    PS = PolygonSelector(ax, onselect)


tk.Button(root, text='draw', command=draw).pack()

root.mainloop()

这是在 tkinter GUI 上单击“绘制”按钮后的图,多边形的起点停留在 (0,0),预计会随光标移动:

http://img4.mukewang.com/6152a7440001e18206380542.jpg

当我draw()在 tkinter 之外调用时,PolygonSelector 工作正常:


def draw():

    fig = plt.figure()

    ax = fig.add_subplot(111)

    plt.ion()    # interactive mode is on

    plt.show()


    def onselect(data_input):

        print(data_input)


    PS = PolygonSelector(ax, onselect)

    a = input()    # prevent window from closing when execution is done

draw()

http://img1.mukewang.com/6152a74c0001575506410543.jpg

胡子哥哥
浏览 168回答 1
1回答

牧羊人nacy

简单的解决方案是确保您将多边形选择器设为全局变量。这将使选择器在视觉上保持更新。#!/usr/bin/env python3import tkinter as tkimport matplotlibimport matplotlib.pyplot as pltfrom matplotlib.widgets import PolygonSelectormatplotlib.use("TkAgg")root = tk.Tk()ps = Nonedef draw():    global ps    fig = plt.figure()    ax = fig.add_subplot(111)    plt.ion()    plt.show()    ps = PolygonSelector(ax, on_select)def on_select(data_input):    print(data_input)tk.Button(root, text='draw', command=draw).pack()root.mainloop()如果将其构建到类中,则可以避免使用 global 并通过将 Polygon Selector 作为类属性应用来获得所需的行为。#!/usr/bin/env python3import tkinter as tkimport matplotlibimport matplotlib.pyplot as pltfrom matplotlib.widgets import PolygonSelectormatplotlib.use("TkAgg")class GUI(tk.Tk):    def __init__(self):        super().__init__()        self.ps = None        tk.Button(self, text='draw', command=self.draw).pack()    def draw(self):        fig = plt.figure()        ax = fig.add_subplot(111)        plt.ion()        plt.show()        self.ps = PolygonSelector(ax, self.on_select)    def on_select(self, data_input):        print(data_input)if __name__ == "__main__":    GUI().mainloop()结果:
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python