来自pyplot问题的Tkinter和秀

时间:2014-06-13 08:34:04

标签: python matplotlib tkinter

以下是上下文:

import numpy as np
import matplotlib.pyplot as pl
from matplotlib.widgets import RectangleSelector

#####################
#  MOUSE CLICK      #
#####################

def line_select_callback(eclick, erelease):
    'eclick and erelease are the press and release events'
    cadre.append(eclick.xdata)
    cadre.append(eclick.ydata)
    cadre.append(erelease.xdata)
    cadre.append(erelease.ydata)

def toggle_selector(event):
    print (' Key pressed.')
    if event.key in ['enter', 'Q', 'q'] and toggle_selector.RS.active:
        print ('Selection done ')
        toggle_selector.RS.set_active(False)
        pl.close()


###########
#  Input  #
###########
from Tkinter import *
import tkFileDialog
import matplotlib.image as mpimg

root = Tk()
root.withdraw()
path = tkFileDialog.askopenfilename(filetypes = [("Image fibre", "*")])

''' some code .... '''

################
#  Select ROI  #
################
fig, current_ax = pl.subplots()                    # make a new plotingrange
cadre = []
pl.imshow(Image, interpolation='none')
# drawtype is 'box' or 'line' or 'none'
toggle_selector.RS = RectangleSelector(current_ax, line_select_callback,
                                       drawtype='box', useblit=True,
                                       button=[1,3], # don't use middle button
                                       minspanx=5, minspany=5,
                                       spancoords='pixels',
                                       rectprops = dict(facecolor='red',
                                           edgecolor ='white',
                                           alpha =0.2,
                                           fill = True),
                                         )
pl.connect('key_press_event', toggle_selector)
pl.title('Select ROI and press \'Enter\'')
pl.show()

print "After closing"

这里的目的是从pyplot中获得一个阻止窗口,直到按下按键“Q'或者'输入'或关闭窗口。当我使用Tkinter窗口关闭但是没有显示"After closing"时(程序似乎阻止)有一个问题。 我尝试将pl.show()替换为fig.show(),但它不是相同的功能,因此窗口不会阻止并继续编程。

注意:如果我删除它,它的效果会很好:

root = Tk()
root.withdraw()

在这种情况下会出现一个空窗口,我必须将其关闭才能正常工作。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我实际上需要销毁我的对象:

root = Tk()
root.withdraw()
path = tkFileDialog.askopenfilename(filetypes = [("Image fibre", "*")])
root.destroy()

答案 1 :(得分:0)

pl.show()启动Tk的主循环。所以,在你退出循环之前永远不要回来。

为此,你必须注册图中的close事件并退出mainloop:

def on_close(event):
    root.quit()

''' some code ...'''

fig, current_ax = pl.subplots()
fig.canvas.mpl_connect('close_event', on_close)

''' some code ...'''

pl.show()
print "After closing"