为了账号安全,请及时绑定邮箱和手机立即绑定

matplotlib PolygonSelector 在 tkinter 中调用时冻结

matplotlib PolygonSelector 在 tkinter 中调用时冻结

胡子哥哥 2021-09-28 13:24:58
我正在使用 tkinter 和 matplotlib 编写脚本进行数据处理,代码的某些部分需要多边形选择器来选择感兴趣的区域。但是,PolygonSelector 无法检测光标的运动。需要注意的是,这个问题是在matplotlib图形交互模式开启的情况下出现的。简化代码和结果如下所示:#!/usr/bin/env python3import matplotlibmatplotlib.use("TkAgg")import tkinter as tkimport matplotlib.pyplot as pltfrom matplotlib.widgets import PolygonSelectorroot = 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),预计会随光标移动:当我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 donedraw()
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

简单的解决方案是确保您将多边形选择器设为全局变量。这将使选择器在视觉上保持更新。


#!/usr/bin/env python3

import tkinter as tk

import matplotlib

import matplotlib.pyplot as plt

from matplotlib.widgets import PolygonSelector

matplotlib.use("TkAgg")



root = tk.Tk()

ps = None


def 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 python3

import tkinter as tk

import matplotlib

import matplotlib.pyplot as plt

from matplotlib.widgets import PolygonSelector

matplotlib.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()

结果:

查看完整回答
反对 回复 2021-09-28
  • 1 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信