如何从wxpython gui的同一按钮中打开两个不同的pylab图形?

问题描述 投票:2回答:3

我是python的新手,我有一个严重的问题,我无法克服。我使用wxpython创建了一个gui,它具有两个文本字段和一个按钮。当按下此按钮时,我调用一个函数,该函数调用另一个函数,该函数根据文本框中的输入创建一个饼图。问题是,如果用户不关闭图形并在文本框中输入新值并再次按下按钮,程序将崩溃,而不是显示第二个图形。当按钮被按下时,我尝试创建不同的线程。

更具体地说:

这是单击按钮时调用的函数:

def statistics_button(self,event):

   t=threading.Thread(target=self.m_button21OnButtonClick,args=(event,))
    t.start()
    print t    

def m_button21OnButtonClick( self, event ):

    '''some code here'''


    fig=statistics.mmr_dist(mmr1,mmr2) 

    show()

首先调用statistics_button,然后调用m_button21OnButtonClick。statistics.mmr_dist函数如下:

'''some code'''
fig=pylab.figure(tit,figsize=(8,8),frameon=False)

ax=pylab.axes([0.1, 0.1, 0.8, 0.8])
pita=pylab.pie(db.values(), labels=tuple(db.keys()), autopct='%1.1f%%', shadow=True)
ti="%s-%s\n Maximum Distance = %s m\n Minimum Distance = %s m" % (ddf1.label,ddf2.label,maxdist,mindist)
title(ti, bbox={'facecolor':'0.8', 'pad':5}) 


'''some code'''

return fig

到目前为止,我已经了解到show()命令会阻止m_button21OnButtonClick函数完成,因此,除非关闭图形,否则单击按钮时将无法再次调用它。但这就是我实现不同线程的原因。尽管它似乎不起作用。

python wxpython matplotlib figure
3个回答
1
投票

请参阅this page,以获得有关使pylab与wxPython一起使用的建议-您可能不应该真正尝试使用它(请参见下一段)。问题是pylab使用的Tkinter与运行的wxPython副本不兼容。

[最后,您应该只输入embed your plots in wxPython。效果很好,无论如何都是更好的用户体验。


0
投票

在导入pylab之后尝试发出命令pylab.ion(),并查看是否可以显示多个图。当需要重复显示更新图而不关闭窗口时,这一直是我的方法。

请注意,您需要为每个不同的绘图窗口创建新的图形和坐标轴对象,否则,绘图将覆盖旧的绘图。

例如,以下代码为我生成了两个具有不同绘图的窗口:

 import pylab
 pylab.ion()

 fig1 = pylab.figure()
 fig1.add_subplot(111).plot([1,2],[3,4])
 pylab.draw()

 fig2 = pylab.figure()
 fig2.add_subplot(111).plot([5,6],[10,9])
 pylab.draw()

已添加

给出您的后续评论,这是一个确实使用show()的新脚本,但是每次调用pylab.draw()时都会显示不同的图,并且使图窗口无限期地显示。它使用简单的输入逻辑来决定何时关闭图形(因为使用show()意味着pylab不会处理Windows x按钮上的点击),但是作为另一个按钮或文本字段添加到gui中应该很简单。

import numpy as np
import pylab
pylab.ion()

def get_fig(fig_num, some_data, some_labels):

    fig = pylab.figure(fig_num,figsize=(8,8),frameon=False)
    ax = fig.add_subplot(111)
    ax.set_ylim([0.1,0.8]); ax.set_xlim([0.1, 0.8]);
    ax.set_title("Quarterly Stapler Thefts")
    ax.pie(some_data, labels=some_labels, autopct='%1.1f%%', shadow=True);
    return fig

my_labels = ("You", "Me", "Some guy", "Bob")

# To ensure first plot is always made.
do_plot = 1; num_plots = 0;

while do_plot:
    num_plots = num_plots + 1;
    data = np.random.rand(1,4).tolist()[0]

    fig = get_fig(num_plots,data,my_labels)
    fig.canvas.draw()
    pylab.draw()

    print "Close any of the previous plots? If yes, enter its number, otherwise enter 0..."
    close_plot = raw_input()

    if int(close_plot) > 0:
        pylab.close(int(close_plot))

    print "Create another random plot? 1 for yes; 0 for no."
    do_plot = raw_input();

    # Don't allow plots to go over 10.
    if num_plots > 10:
        do_plot = 0

pylab.show()

0
投票

如果要在wxPython中创建饼形图或其他类型的图形,则应使用PyPlot(包含在wx中)或matplotlib,它们可以嵌入wxPython中。 wxPython演示有一个PyPlot示例。关于matplot,请参见herehere

© www.soinside.com 2019 - 2024. All rights reserved.