我正在处理图像数据库,并希望显示在wx.StaticBitmap对象中处理的每个图像。据我所知,函数onView中的这一行“ self.imageCtrl.SetBitmap(wx.Bitmap(self.img))”应该会更改图像。但是我什么也做不了。该代码是从我的探索得到的答案,并且是图像显示应用程序的一部分,该应用程序每次单击按钮都会更改图像。效果很好,但是一旦将代码嵌入循环中,它就无法刷新,直到循环完成,最后显示最后一个文件为止。
import time
import os
import wx
#============ App and panel class ========#
class PhotoCtrl(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
self.frame = wx.Frame(None, title='Photo Control')
self.panel = wx.Panel(self.frame)
self.PhotoMaxSize = 256
self.createWidgets()
self.frame.Show()
#=========== Set up button, wx.StaticBitmap etc ===============#
def createWidgets(self):
#instructions = 'Browse for an image'
img = wx.Image(256,256)
self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.Bitmap(img))
browseBtn = wx.Button(self.panel, label='Go')
browseBtn.Bind(wx.EVT_BUTTON, self.onView)
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(wx.StaticLine(self.panel, wx.ID_ANY),
0, wx.ALL|wx.EXPAND, 5)
#self.mainSizer.Add(instructLbl, 0, wx.ALL, 5)
self.mainSizer.Add(self.imageCtrl, 0, wx.ALL, 5)
#self.sizer.Add(self.photoTxt, 0, wx.ALL, 5)
self.sizer.Add(browseBtn, 0, wx.ALL, 5)
self.mainSizer.Add(self.sizer, 0, wx.ALL, 5)
self.panel.SetSizer(self.mainSizer)
self.mainSizer.Fit(self.frame)
self.panel.Layout()
#=== Toy code to simulate automatic change of image to be displayed ===#
def onView(self, event):
for i in range(1,10):
im_pth = os.getcwd() + f'/Cats/cats/Cats_{i}.png'
self.img = wx.Image(im_pth, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.image = self.img.ConvertToImage()
self.img = wx.Bitmap(self.image.Scale(256, 256))
self.imageCtrl.SetBitmap(wx.Bitmap(self.img))
self.panel.Refresh()
print(f"should be showing cat_{i}") #This prints but the image doesn't show
time.sleep(1)
if __name__ == '__main__':
app = PhotoCtrl()
app.MainLoop()
答案 0 :(得分:1)
这是因为您处于循环状态,不会将控制权释放回mainloop
。
您需要Yield
之前time.sleep(1)
即
def onView(self, event):
for i in range(1,10):
im_pth = os.getcwd() + f'/frame{i}.png'
self.img = wx.Image(im_pth, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.image = self.img.ConvertToImage()
self.img = wx.Bitmap(self.image.Scale(256, 256))
self.imageCtrl.SetBitmap(wx.Bitmap(self.img))
self.panel.Refresh()
wx.Yield()
print(f"should be showing cat_{i}") #This prints but the image doesn't show
time.sleep(1)
严格来说,在wxPython Phoenix下,应该为wx.GetApp().Yield()
但wx.Yield()
仍然有效。