wxPython Transparent Bitmap on Custom Control with PaintDC - python

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.

Related

Disable windows border with wxpython and cefpython3

I am following this example https://github.com/cztomczak/cefpython/blob/master/examples/wxpython.py for cefpython3 and wxpython. However I am looking to disable the windows border so the program can no longer be adjusted size wise and their is no title bar. But I would like to keep it so the program can be moved around the screen. I have done some research but not come across a way to successfully do this.
The following appears to do the job on Linux.
Your mileage may vary.
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id=wx.ID_ANY, title="", size=(360,100)):
super(MyFrame, self).__init__(parent, id, title, size, style = wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX))
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour('palegreen')
self.Show()
if __name__ == "__main__":
app = wx.App()
frame = MyFrame(None,title="Non-Resizeable Frame")
app.MainLoop()

Database Loading Panel Screen StaticText is Blurred Out when Shown

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...

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.

How to reference currently open dialog box?

I'm creating an app using Eric4 and PyQt4.
I have two dialog boxes, one runs as a thread and the other is a standard dialog box with a label inside, which I want to change to an image.
Every time the main window thread runs I want it to change the current image displayed in the dialog box to a new image. Everything works fine except every time the thread runs it creates a new dialog box with the new image inside - I want it to change the image in the dialog box that's currently open.
Dialog box with image inside:
class SubWindow(QDialog, Ui_subWindow):
def __init__(self, parent = None):
QDialog.__init__(self, parent)
self.setupUi(self)
self.show()
def main(self, img):
pic = self.imgView
pic.setPixmap(QtGui.QPixmap(os.getcwd() + img))
Thread which changes the image:
class MainWindow(QDialog, Ui_MainWindow, threading.Thread):
def __init__(self, parent = None):
threading.Thread.__init__(self)
QDialog.__init__(self, parent)
self.setupUi(self)
self.show()
#some code here which does some stuff then calls changeImg()
def changeImg(self):
img = SubWindow()
img.main(img)
I've not included all my code, only the relevant bits.
It looks like the problem is that you are creating a new SubWindow every time you wish to change the image. I would recommend creating the SubWindow as an attribute to MainWindow in the MainWindiw.__init__ function:
class MainWindow(QDialog, Ui_MainWindow, threading.Thread):
def __init__(self, parent = None):
threading.Thread.__init__(self)
QDialog.__init__(self, parent)
self.setupUi(self)
self.show()
self.img = SubWindow() # Create SubWindow once here
def changeImg(self):
self.img.main(self.img) # Only change the image, no new SubWindow

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/

Categories

Resources