2011-08-11 46 views
0

我正在使用tkinter编写一个简单的GUI程序来绘制一些数据的图形,plot函数是使用matplotlib模块实现的,这里是我的简化代码:让Tkinter继续处理下一个事件,不关闭当前弹出窗口

#!/usr/bin/env python 
import Tkinter, tkFileDialog, tkMessageBox 
from plot_core import berplot 

class BerPlotTk(Tkinter.Frame): 
    def __init__ (self, master = None): 
     Tkinter.Frame.__init__(self, master, width = 500, height = 200) 
     self.fullfilenames = [] # filename with path    
     self.master = master 
     self.CreateWidgets() 

    def CreateWidgets(self): 
     # other widgets... 

     # Buttons 
     self.button_sel = Tkinter.Button(self, text = "Open", command = self.Open)       
     self.button_sel.grid(column = 0, row = 7, sticky = "EW") 
     self.button_plot = Tkinter.Button(self, text = "Plot", command = self.Plot)            
     self.button_plot.grid(column = 2, row = 7, sticky = "EW")    
     self.button_exit = Tkinter.Button(self, text = "Exit", command = self.top.quit)            
     self.button_exit.grid(column = 3, row = 7, sticky = "EW") 

    def Open(self): 
     input_filenames = tkFileDialog.askopenfilename(parent = self.master, 
            title = "Select the log file") 
     self.fullfilenames = list(self.tk.splitlist(input_filenames)) 

    def Plot(self): 
     berplot(self.fullfilenames)    


if __name__ == "__main__": 
    root = Tkinter.Tk() 
    app = BerPlotTk(root) 
    root.mainloop() 
    root.destroy() 

berplot()是另一个Python模块的功能:

from matplotlib.pyplot import * 
def berplot(filelist): 

    # retrieve data x, y from the log file 
    # ...   
    ber = semilogy(x, y) 
    # ... 
    show() 
    return 1 

该程序可以正常工作,当我打开数据文件,然后单击“绘图”按钮,它会创建一个图形窗口(通过matplotlib),但是在关闭图形w之前GUI不能继续处理indow。但是,我想继续在保持当前状态的情况下绘制下一个图形,我怎么能意识到这一点?

回答

1

可以嵌入matplotlib图中Tk的GUI:

import matplotlib 
matplotlib.use('TkAgg') 

from numpy import arange, sin, pi 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg 
from matplotlib.figure import Figure 
import Tkinter as Tk 

class TkPlot(Tk.Frame): 
    def __init__ (self, master = None): 
     Tk.Frame.__init__(self, master, width = 500, height = 200) 
     self.CreateWidgets() 

    def CreateWidgets(self): 
     self.button = Tk.Button(root, text="Plot", command=self.Plot) 
     self.button.pack() 
     self.figure = Figure(figsize=(5,4), dpi=100) 

     canvas = FigureCanvasTkAgg(self.figure, master=root) 
     canvas.show() 
     canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) 

     toolbar = NavigationToolbar2TkAgg(canvas, root) 
     toolbar.update() 
     canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1) 

    def Plot(self): 
     a = self.figure.add_subplot(111) 
     t = arange(0.0,3.0,0.01) 
     s = sin(2*pi*t) 
     a.plot(t,s) 
     self.figure.canvas.draw() 

if __name__ == "__main__": 
    root = Tk.Tk() 
    app = TkPlot(root) 
    root.mainloop() 

http://matplotlib.sourceforge.net/examples/user_interfaces/index.html

+0

谢谢,我用你的方法解决了这个问题。 – platinor