Database Loading Panel Screen StaticText is Blurred Out when Shown - python

Database Loading Panel Screen StaticText is Blurred Out when Shown
Hello,
I have an odd issue with a loading screen. The problem is this: When I start with a main screen, then when you click on the 'next' button,
it goes to the database loading screen, when it is done, it prints on the screen that the Database Loading is complete.
The problem is that the loading screen text is blurred out for some reason. Also, something I discovered is that if you pop up a message dialog
box, the loading text is shown...
In this example, I am not actually loading into an actual database. Instead, I am just sleeping for seven seconds.
If you are confused as to what I am saying, just run the example, and you will see that the loading screen is all messed up...
Here is the code:
import wx
import time
class TextPanel(wx.Panel):
def __init__(self, parent, label):
self.__myParent = parent
wx.Panel.__init__(self, self.__myParent, size = (800, 800))
staticText = wx.StaticText(self, label = label)
class MainPanel(wx.Panel):
def __init__(self, parent):
self.__myParent = parent
wx.Panel.__init__(self, self.__myParent, size = (800, 800))
nextButton = wx.Button(self, label = 'Next')
nextButton.Bind(wx.EVT_BUTTON, self.__onNext)
def __onNext(self, event):
self.__myParent.onNextScreen()
class MainFrame(wx.Frame):
def __init__(self):
# Base contsructor.
wx.Frame.__init__(self, None, id = -1, title = 'Testing...', size = (800, 800))
self.__myMainPanel = MainPanel(self)
self.__myMainPanel.Show()
self.__myDatabase = TextPanel(self, 'Loading Data...')
self.__myDatabase.Hide()
self.__myFinalPanel = TextPanel(self, 'Database Loading Complete!')
self.__myFinalPanel.Hide()
def onNextScreen(self):
self.__myMainPanel.Hide()
self.__myDatabase.Show()
self.doDatabaseLoad()
self.__myDatabase.Hide()
self.__myFinalPanel.Show()
def doDatabaseLoad(self):
time.sleep(7) # before, this method would load data into a database...
if __name__ == '__main__':
app = wx.App()
frame = MainFrame()
frame.Show(True)
app.MainLoop()
print 'Exiting...'

Thanks all for your help,
I found an easy solution to this issue.
I first found out that wx.Panel.Update() gets called to repaint the screen when ever the event handler method returns. So, the loading panel seems to look like it needed to be repainted, as the static text box is all grayed out. I then just called self.__myDatabase.Update() after self.__myDatabase.Show().
Here is the new version of onNextScreen(self):
def onNextScreen(self):
self.__myMainPanel.Hide()
self.__myDatabase.Show()
self.__myDatabase.Update() # Fixes the bug...
self.doDatabaseLoad()
self.__myDatabase.Hide()
self.__myFinalPanel.Show()
Also, another way to fix it is to call SetLabel on the static text, but the above solution is better. It just seems that Update was not being called automatically, because it was in the middle of an event...

Related

wxPython Transparent Bitmap on Custom Control with PaintDC

I am writing a custom button control in wxPython 4.1.1 on Python 3.9.12 using MacOS 12.2. The custom button uses a bitmap background with text written on it. The bitmap is transparent so parts of underlying controls can be seen through it. This worked in 4.0.7-Pre2, but no longer. I have reduced the problem to the use of MemoryDC to create a a buffered copy of the background image.When BufferedPaintDC or MemoryDC are used, the alpha channel disappears and the transparent region is black. However, if I don't use a buffered DC and draw directly on the control, everything still works. Why is this?
The minimum code to reproduce looks like:
import wx
class MyButton(wx.Control):
def __init__(self, parent, id, text, **kwargs):
wx.Control.__init__(self,parent, id, **kwargs)
self.Bind(wx.EVT_PAINT,self._onPaint)
self.myBG = self.MakeBG()
def MakeBG(self):
newBG = wx.Bitmap(50,50)
mdc = wx.MemoryDC()
mdc.SelectObject(newBG)
mdc.SetBackground(wx.Brush(wx.Colour(0,0,255, wx.ALPHA_TRANSPARENT)))
mdc.Clear()
mdc.DrawText("HELLO", 0,0)
return newBG
def _onPaint(self, event):
dc = wx.PaintDC(self)
dc.DrawBitmap(self.myBG, 0,0, True)
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(200,100))
button = MyButton(self, -1 , "TEST BUTTON")
self.BackgroundColour = wx.Colour(255,0,0)
self.Show(True)
self.Refresh()
if __name__ == "__main__":
app = wx.App(False) # Create a new app, don't redirect stdout/stderr to a window.
frame = MyFrame(None, "Hello World") # A Frame is a top-level window.
app.MainLoop()
However, if I change the paint event to not use the bitmap and draw directly with the PaintDC, it works.
def _onPaint(self, event):
dc = wx.PaintDC(self)
dc.SetBackground(wx.Brush(wx.Colour(0,0,255, wx.ALPHA_TRANSPARENT)))
dc.Clear()
dc.DrawText("HELLO", 0,0)
I think the problem is with retaining the alpha channel, but I think something deeper is wrong because a BufferedPaintDC also has the same problem.

Panel doesn't fully refresh when using a custom background in wxPython

Here's some sample code:
import wx
class MainPanel(wx.Panel):
p1 = None
p2 = None
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent)
self.frame = parent
#self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
#self.bg = wx.Bitmap("2.jpg")
self.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.p2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.p1 = event.GetPosition()
def OnPaint(self, event):
if self.p1 is None or self.p2 is None: return
dc = wx.PaintDC(self)
dc.SetPen(wx.Pen('red', 3, wx.LONG_DASH))
dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.SOLID))
dc.DrawRectangle(self.p1.x, self.p1.y, self.p2.x - self.p1.x, self.p2.y - self.p1.y)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size=(600,450))
panel = MainPanel(self)
self.Center()
class Main(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
dlg = MainFrame()
dlg.Show()
if __name__ == "__main__":
app = Main()
app.MainLoop()
The two offending lines are:
#self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
#self.bg = wx.Bitmap("2.jpg")
If you run the code like that, you're able to draw a rectangle on the panel. If you start a new rectangle, the old one disappears, because the panel is refreshing.
However, if you uncomment those two lines, when you draw a rectangle, it stays there. You can have infinite number of rectangles. If I use dc.Clear(), the background disappears and reloading the background makes the application slow and it flickers.
How do I make the panel fully refresh while using a custom background?
By the way, the background image doesn't load with this code, but the behavior is the same.
EDIT: I found a workaround to the flickering caused by using dc.Clear() and reloading the background. Setting double buffering on the panel to true solves the flickering:
self.SetDoubleBuffered(True)
I will use that, but I'll leave the question open in case someone knows the answer to the initial problem.
When using the wx.BG_STYLE_CUSTOM background style it assumes that you will paint (or clear) the entire window in the EVT_PAINT event handler. The easiest way to do that without flicker is to only push pixels to the screen one time per paint event.
Using SetDoubleBuffered does that at the system level, although that has been known to have side-effects in some cases. Another easy way is to use a wx.BufferedPaintDC instead of wx.PaintDC. It will create a bitmap that is the target of all the drawing operations and then at the end the contents of the bitmap will be flushed to the screen.

Flicker with wxpython displaying webcam video

I am new to python. I am trying to write a motion detection app. Currently, I am trying to get the webcam video to display on the screen. Current code right now has no flicker at first, but after any resizing, the flicker will come back. Any clue? Also, why doesn't it work without self.Refresh() in the timer event, isn't paint event always happening unless the frame is minimized? Thanks in advance.
import wx
import cv
class LiveFrame(wx.Frame):
fps = 30
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, title="Live Camera Feed")
self.SetDoubleBuffered(True)
self.capture = None
self.bmp = None
#self.displayPanel = wx.Panel(self,-1)
#set up camaera init
self.capture = cv.CaptureFromCAM(0)
frame = cv.QueryFrame(self.capture)
if frame:
cv.CvtColor(frame,frame,cv.CV_BGR2RGB)
self.bmp = wx.BitmapFromBuffer(frame.width,frame.height,frame.tostring())
self.SetSize((frame.width,frame.height))
self.displayPanel = wx.Panel(self,-1)
self.fpstimer = wx.Timer(self)
self.fpstimer.Start(1000/self.fps)
self.Bind(wx.EVT_TIMER, self.onNextFrame, self.fpstimer)
self.Bind(wx.EVT_PAINT, self.onPaint)
self.Show(True)
def updateVideo(self):
frame = cv.QueryFrame(self.capture)
if frame:
cv.CvtColor(frame,frame,cv.CV_BGR2RGB)
self.bmp.CopyFromBuffer(frame.tostring())
self.Refresh()
def onNextFrame(self,evt):
self.updateVideo()
#self.Refresh()
evt.Skip()
def onPaint(self,evt):
#if self.bmp:
wx.BufferedPaintDC(self.displayPanel, self.bmp)
evt.Skip()
if __name__=="__main__":
app = wx.App()
app.RestoreStdio()
LiveFrame(None)
app.MainLoop()
I have found the solution to this problem. The flickering came from the panel clearing its background. I had to create a panel instance and have its EVT_ERASE_BACKGROUND bypass. Another thing is that I had to put the webcam routine inside that panel and have BufferPaintedDC drawing on the panel itself. For some reason, flicker still persist if wx.BufferedPaintedDC is drawing from the frame to self.displaypanel .
When you're drawing, you just have to call Refresh. It's a requirement. I don't remember why. To get rid of flicker, you'll probably want to read up on DoubleBuffering: http://wiki.wxpython.org/DoubleBufferedDrawing
Or maybe you could use the mplayer control. There's an example here: http://www.blog.pythonlibrary.org/2010/07/24/wxpython-creating-a-simple-media-player/

wx.Media video load ....Video file not playing

I want to start playing a .wmv file as soon as it is loaded in wxPython. I wrote a small code for it. The code does not give any error, but it does not show any video as well, but the sound does play in the background. It just shows a gray screen. Following is the code I wrote for my program.
import wx
import wx.media
class TestPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1, style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN)
# Create some controls
try:
self.mc = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)
except NotImplementedError:
self.Destroy()
raise
self.mc.Load(r"C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
#self.slider.SetRange(0, self.mc.Length())
#folder, filename = os.path.split("C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
self.Bind(wx.media.EVT_MEDIA_LOADED, self.OnPlay)
def OnPlay(self,evt):
self.mc.Play()
app = wx.App(0)
frame = wx.Frame(None)
panel = TestPanel(frame)
frame.Show()
app.MainLoop()
I am using Python 2.7 and windows XP.
Can anyone please help me on this one. I would be really grateful for your help.

How to adapt my current splash screen to allow other pieces of my code to run in the background?

Currently I have a splash screen in place. However, it does not work as a real splash screen - as it halts the execution of the rest of the code (instead of allowing them to run in the background).
This is the current (reduced) arquitecture of my program, with the important bits displayed in full. How can I adapt the splash screen currently in place to actually allow the rest of the program to load in the background? Is it possible in python?
Thanks!
import ...
(many other imports)
def ...
def ...
(many other definitions)
class VFrams(wxFrame):
wx.Frame.__init__(self, parent, -1, _("Software"),
size=(1024, 768), style=wx.DEFAULT_FRAME_STYLE)
(a lot of code goes in here)
class MySplashScreen(wx.SplashScreen):
def __init__(self, parent=None):
aBitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT
splashDuration = 5000 # ms
wx.SplashScreen.__init__(self, aBitmap, splashStyle, splashDuration, parent)
self.Bind(wx.EVT_CLOSE, self.CloseSplash)
wx.Yield()
def CloseSplash(self, evt):
self.Hide()
global frame
frame = VFrame(parent=None)
app.SetTopWindow(frame)
frame.Show(True)
evt.Skip()
class MyApp(wx.App):
def OnInit(self):
MySplash = MySplashScreen()
MySplash.Show()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars()
Start_Menus()
Start_Event_Handlers()
app = MyApp()
app.MainLoop()
Thank you for all the help, this is how I changed the code (following the provided advice):
def show_splash():
# create, show and return the splash screen
global splash
bitmap = wx.Image(name=VarFiles["img_splash"]).ConvertToBitmap()
splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
splash.Show()
return splash
class MyApp(wx.App):
def OnInit(self):
global frame, splash
splash = show_splash()
Start_Config()
Start_Translation()
Start_DB()
Start_Themes()
Start_Gui()
Start_Get_Isos()
Start_Bars("GDP1POP1_20091224_gdp", "1 pork")
Start_Menus()
Start_Event_Handlers()
frame = VFrame(parent=None)
frame.Show(True)
splash.Destroy()
return True
if __name__ == '__main__':
DEBUG = viz.addText('DEBUG:', viz.SCREEN)
DEBUG.setPosition(0, 0)
DEBUG.fontSize(16)
DEBUG.color(viz.BLACK)
Start_Mainvars()
app = MyApp()
app.MainLoop()
Your code is pretty messy/complicated. There's no need to override wx.SplashScreen and no reason your splash screen close event should be creating the main application window. Here's how I do splash screens.
import wx
def show_splash():
# create, show and return the splash screen
bitmap = wx.Bitmap('images/splash.png')
splash = wx.SplashScreen(bitmap, wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_NO_TIMEOUT, 0, None, -1)
splash.Show()
return splash
def main():
app = wx.PySimpleApp()
splash = show_splash()
# do processing/initialization here and create main window
frame = MyFrame(...)
frame.Show()
splash.Destroy()
app.MainLoop()
if __name__ == '__main__':
main()
Just create the splash screen as soon as possible with no timeout. Continue loading and create your application's main window. Then destroy the splash screen so it goes away. Showing the splash screen doesn't stop other processing from happening.
You'll want to use two threads: one for the splash screen, one for whatever other code you want to execute. Both threads would run at the same time, providing the result you desire.

Categories

Resources