我有一个用wxPython (some extra information can be found in a different question) )编写的GUI。GUI有指示器(图表、文本等)和控件(按钮、无线电盒等)。我经常会得到新的数据来绘制。这取决于数据集的大小,它可能需要20秒的时间来生成和绘制图形。在此期间,GUI控件没有响应,因为GUI线程忙于图表绘制。
如何使GUI控件始终响应,而不考虑我正在绘制的数据集的大小?
发布于 2018-09-06 14:31:06
这是解决这个问题的办法。简而言之,
请看下面的代码。
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
https://stackoverflow.com/questions/52206292
复制相似问题