我有一个用wxPython(some extra information can be found in a different question)编写的GUI。该GUI有指示器(图表,文本等)和控件(按钮,单选框等)。每隔一段时间我就会获得新的数据进行绘制。该数据集的大小最多可能需要20秒钟才能生成图形并绘制它。在此期间,由于GUI线程忙于绘制图表,因此GUI控件没有响应。
无论我要绘制的数据集大小如何,如何使GUI控件始终响应?
答案 0 :(得分:0)
这是解决此问题的方法。简短地,
请参见下面的代码。
frame = wx.Frame.__init__(self, None, wx.ID_ANY, "", size = (1200,800))#, style= wx.SYSTEM_MENU | wx.CAPTION)
self.panel = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_THEME, size = (1200,800))
#bmp1 = wx.Bitmap.FromRGBA(100, 100, red=255, alpha=0)
self.bitmap1 = wx.StaticBitmap(self.panel)
self.bitmap2 = wx.StaticBitmap(self.panel)
sizer = wx.GridBagSizer(hgap = 0, vgap = 0)#(13, 11)
sizer.Add(self.bitmap1, pos=(0,0), flag = wx.ALL)#, flag=wx.TOP|wx.RIGHT) FIXIT so the sidebar is closer to the graph
sizer.Add(self.bitmap2, pos=(1,0), flag = wx.ALL)#,flag=wx.TOP|wx.RIGHT)
def buf2wx (buf):
import PIL
image = PIL.Image.open(buf)
width, height = image.size
return wx.Bitmap.FromBuffer(width, height, image.tobytes())
#access the buffer which was created in a different thread
#or use socket to retrieve it from a remote server or
#whatever you might want to do.
buf = get_buf_from_somewhere()
self.bitmap1.SetBitmap(buf2wx(buf))
self.bitmap2.SetBitmap(buf2wx(buf))
self.panel.SetSizer(sizer)
self.Layout()
self.panel.Layout()
self.Fit()
在不同线程中甚至在远程服务器上运行的代码段。这段代码将生成一个图并将其保存在GUI可以读取或转移到其他位置的文件中。
def plot():
from matplotlib import pyplot as plt
import io
from numpy import random
plt.figure()
b = random.rand(100,)
plt.subplot(311)
plt.plot(b)
b = random.rand(100,)
plt.subplot(312)
plt.plot(b)
b = random.rand(100,)
plt.subplot(313)
plt.plot(b)
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format='jpg')
buf.seek(0)
return buf