I am having some confusing behavior in wxpython. I just loaded the newest version (3.0.0.0) into a RHEL 6.4 with Python 2.6.6.
Most things seem to work, but my previous code for running a gui with a background image fails. All the buttons work, etc, but the background is just the default gray one.
I tried tracking down the problem by running this minimal example from Mike Driscoll's python website (http://www.blog.pythonlibrary.org/2010/03/18/wxpython-putting-a-background-image-on-a-panel/), and had the same problem with no background showing up other than the default gray one (I previously used his example on another machine with an older version of wxpython [2.8.12.1] with no problems):
import wx
########################################################################
class MainPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent=parent)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.frame = parent
sizer = wx.BoxSizer(wx.VERTICAL)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
for num in range(4):
label = "Button %s" % num
btn = wx.Button(self, label=label)
sizer.Add(btn, 0, wx.ALL, 5)
hSizer.Add((1,1), 1, wx.EXPAND)
hSizer.Add(sizer, 0, wx.TOP, 100)
hSizer.Add((1,1), 0, wx.ALL, 75)
self.SetSizer(hSizer)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
#----------------------------------------------------------------------
def OnEraseBackground(self, evt):
"""
Add a picture to the background
"""
# yanked from ColourDB.py
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap("butterfly.jpg")
dc.DrawBitmap(bmp, 0, 0)
########################################################################
class MainFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, size=(600,450))
panel = MainPanel(self)
self.Center()
########################################################################
class Main(wx.App):
""""""
#----------------------------------------------------------------------
def __init__(self, redirect=False, filename=None):
"""Constructor"""
wx.App.__init__(self, redirect, filename)
dlg = MainFrame()
dlg.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":
app = Main()
app.MainLoop()
Now, when I run this, I don't get any errors, but I determined that the function onEraseBackground never seems to run. I don't know what is going wrong here; did wxpython 3.0.0.0 stop allowing this kind of image background setting procedure?
Try commenting out the
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
line. Some other people have experienced the same issue and this line was the culprit - it prevents the EVT_ERASE_BACKGROUND event being triggered.
You can also try replacing this line with
self.SetBackgroundStyle(wx.BG_STYLE_ERASE)
to ensure the erase events are triggered.
Related
I'm trying to make a GUI with on the left side a camera input with some data on the camera stream. On the right side I want some buttons and other widgets. The code a have so far: (the functions get_image() and pil_to_wx() work fine, they're just not shown in the code below)
class HUDPanel(wx.Panel):
def __init__(self, parent):
super(HUDPanel, self).__init__(parent, -1)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.Bind(wx.EVT_PAINT, self.on_paint)
self.update()
def update(self):
self.Refresh()
self.Update()
wx.CallLater(15, self.update)
def create_bitmap(self):
image = get_image()
bitmap = pil_to_wx(image)
return bitmap
def on_paint(self, event):
bitmap = self.create_bitmap()
dc = wx.AutoBufferedPaintDC(self)
dc.DrawBitmap(bitmap, 0, 0)
class ExtraPanel(wx.Panel):
def __init__(self, parent):
super(ExtraPanel, self).__init__(parent, -1)
My_Button = wx.Button(self,label="TEST")
class Frame(wx.Frame):
def __init__(self):
style = wx.DEFAULT_FRAME_STYLE & ~wx.RESIZE_BORDER & ~wx.MAXIMIZE_BOX
super(Frame, self).__init__(None, -1, 'Camera Viewer', style=style)
my_sizer = wx.BoxSizer(wx.HORIZONTAL)
campanel = HUDPanel(self)
my_sizer.Add(campanel, 0, wx.ALL | wx.CENTER, 5)
widgetpanel = ExtraPanel(self)
my_sizer.Add(widgetpanel, 0, wx.ALL | wx.CENTER, 5)
self.SetSizer(my_sizer)
self.Fit()
def main():
app = wx.App()
frame = Frame()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
When I run this code, all I get is a small window with only a button named "TEST" (the panel that should be on the right side). The previous version with only the camera panel worked fine, so that's not the problem. What am I doing wrong?
UPDATE:
The sizes of the sub-panels are fixed, i see the panel with the camera show up but only a small line on the screen. The part with the button show perfectly.
First of all, you don't give any size to your HUDPanel, so I'm not sure how do you expect it to appear.
Second, you're recursively calling update all the time (well every 15ms), which is most definitely a bad idea as this will consume close to 100% of (one) CPU and may prevent your application from dispatching other events.
I'm creating a wx.agw.SuperToolTip. I'm updating the message in the tip every few seconds, and if the tip is showing when the message updates the tip is redrawn in a different position.
The new position seems to be relative to the original position's relation to the top left corner of the screen, but that could just be coincidence.
Also, if I modify wx.lib.agw.supertooltip.ToolTipWindowBase.Invalidate() by commenting out the call to self.CalculateBestSize() the problem goes away. Of course then the window won't resize, so that's no solution.
I'm using wxPython 2.8.12.1.
Here's an app that demonstrates the problem:
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, -1, title,
pos=(150, 150), size=(350, 225))
panel = wx.Panel(self)
btn = wx.Button(panel, -1, "Hover over this")
self._superTip = SuperToolTip("")
self._superTip.SetHeader("Heyo!")
self._superTip.SetTarget(btn)
self._superTip.EnableTip(True)
self._superTip.SetDrawHeaderLine(True)
self._superTip.SetDrawFooterLine(True)
self._superTip.SetStartDelay(1)
self._superTip.SetEndDelay(60)
currentFooterFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
currentFooterFont.SetPointSize(6)
currentFooterFont.SetWeight(wx.NORMAL)
self._superTip.SetFooterFont(currentFooterFont)
self._superTip.SetFooter('(Click to close)')
self._superTip.ApplyStyle("Blue Glass")
self._superTip.SetDropShadow(True)
self.ttTimer = wx.Timer(self)
self.ttText = 'What the?'
self.Bind(wx.EVT_TIMER, self.onTimer, self.ttTimer)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(btn, 0, wx.ALL, 10)
panel.SetSizer(sizer)
self.ttTimer.Start(2000)
panel.Layout()
def onTimer(self, evt):
self._superTip.SetMessage(self.ttText)
self.ttText += '?'
class MyApp(wx.App):
def OnInit(self):
frame = MyFrame(None, "STT error demo")
self.SetTopWindow(frame)
frame.Show(True)
return True
app = MyApp(redirect=True)
app.MainLoop()
Any thoughts on how I can update a visible tooltip without its location changing?
Thanks a lot.
I'm using wx.Bitmap's GetSubBitmap() API. On linux (ubuntu, fedora) everything OK. Trying to port code to windows7, GetSubBitmap() return empty bitmap, which result in black bitmap.
Here is simple example that draws periodically green rectangle somewhere on panel. On windows7 it turn to black rectangle.
import wx
import random
class mypanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.buffer = wx.EmptyBitmap(700, 500)
self.SetBackgroundColour("BLUE")
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.ID_TIMER = 1
self.timer = wx.Timer(self, self.ID_TIMER)
self.Bind(wx.EVT_TIMER, self.OnTimer, id=self.ID_TIMER)
self.timer.Start(1000, wx.TIMER_CONTINUOUS)
self.BufferPaint()
self.Refresh(False)
def OnTimer(self, event):
print "OnTimerEvent " + str(event.Id)
self.BufferPaint()
def BufferPaint(self):
dc = wx.MemoryDC()
dc.SelectObject(self.buffer)
dc.SetBackground(wx.Brush("green"))
dc.Clear()
sub = self.buffer.GetSubBitmap(wx.Rect(5,5,30,30))
dc.SetBackground(wx.Brush("red"))
dc.Clear()
dc.DrawBitmap(sub, random.randint(0,600), random.randint(0,400))
self.Refresh(False)
def OnPaint(self, event=None):
dc = wx.BufferedPaintDC(self, self.buffer)
class myframe(wx.Frame):
"""Draw a line to a panel."""
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="Draw on Panel", size=(800,600))
self.panel1 = mypanel(self)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.panel1, 2, wx.EXPAND)
self.SetSizer(self.sizer)
app = wx.App(False)
frame = myframe(None)
frame.Show()
app.MainLoop()
def BufferPaint(self):
dc = wx.MemoryDC()
dc.SelectObject(self.buffer)
dc.SetBackground(wx.Brush("red"))
dc.Clear()
dc.SetBrush(wx.Brush("green"))
dc.DrawRectangleRect( wx.Rect(random.randint(0,600),random.randint(0,400),30,30) )
self.Refresh(False)
I modified BufferPaint in your sample code to use DrawRectangleRect so that we explicitly paint with "green". Your code may be relying on default behavior how GetSubBitmap inherit the color which may be platform dependent.
My edit worked on my win7 machine.
I noticed I can have a help string appear in the status bar whenever I mouse over tools in my toolbar. I cannot find a way to accomplish this with text buttons.
My toolbar creation is similar to
# Make Tool Bar
toolbar = self.CreateToolBar()
# Make Tool Bar Items
# Play
self.addBasicTool(toolbar, "Play",
"This is my help string",
stuff.image_play,
self.OnPlay)
# My Button
btn = wx.Button(toolbar, wx.ID_OPEN, label="TEXT BUTTON ")
btn.Bind(wx.EVT_BUTTON, self.OnButtonPress)
toolbar.AddControl(btn)
addBasicTool just takes the image, scales it to a proper size, creates the tool with AddBasicTool, and binds the tool to the handler.
def addBasicTool(self, toolbar, label, desc, imgPath, handler):
icon_width=stuff.toolbar_icon_w
icon_height=stuff.toolbar_icon_h
size = (icon_width, icon_height)
img = wx.Image(imgPath, wx.BITMAP_TYPE_ANY).\
Scale(*size).ConvertToBitmap()
tool = toolbar.AddSimpleTool(-1, img, label, desc)
self.Bind(wx.EVT_MENU, handler, tool)
For the tool, the helper string is set pretty straight forward. I can't find anything to do the same with a button.
This button may just end up being a filler until I get an icon for it, but I'm still curious how helper strings can be done. I could have a handler that sets the statusBar when the mouse is over the button, but I feel like that is already done somewhere. Thanks the help
Basically you'll have to catch the mouse as it moves over your buttons and update the status bar accordingly. It's not very hard. You just need to bind to wx.EVT_MOTION. Here's a simple example:
import wx
########################################################################
class MyPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent)
self.frame = parent
test_btn = wx.Button(self, label='Test Button')
test_btn.Bind(wx.EVT_MOTION, self.updateStatusBar)
test_btn_2 = wx.Button(self, label='Test Button')
test_btn_2.Bind(wx.EVT_MOTION, self.updateStatusBar)
self.buttons = {test_btn: 'Test help string',
test_btn_2: 'Another string'}
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(test_btn, 0, wx.ALL, 5)
main_sizer.Add(test_btn_2, 0, wx.ALL, 5)
self.SetSizer(main_sizer)
#----------------------------------------------------------------------
def updateStatusBar(self, event):
""""""
btn = event.GetEventObject()
if btn in self.buttons:
status = self.buttons[btn]
self.frame.sb.SetStatusText(status)
########################################################################
class MyFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title='Test Help Strings')
panel = MyPanel(self)
self.sb = self.CreateStatusBar()
self.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
In wxpython, I want to have a window with a picture that changes based on use of toolbar buttons with text controls on top of the picture. When I click the toolbar buttons, I am posting an erase background event, then capturing the erase event, and redrawing the new background from there (base on this).
Mostly works well, except that the text controls cease to be drawn once I redraw the background. They're still there, just not drawn.
Here is a simplified code that demonstrates the problem. If you run this code and click the button to toggle drawing the background image or not, the text controls disappear.:
import wx
import wx.lib.inspection
class PanelWithDrawing(wx.Panel):
def __init__(self, parent):
super(PanelWithDrawing, self).__init__(parent, size=(100, 40))
self.showbmp = False
self.txt = wx.TextCtrl(self, pos=(10, 10))
def onErase(self, dc):
if self.showbmp:
# dc.DrawBitmap(wx.Bitmap('background.png', 0, 0)
dc.DrawRectangle(0, 0, 40, 40) # use a drawing instead so you don't have to find a png
class Toolbar(wx.ToolBar):
def __init__(self, parent):
super(Toolbar, self).__init__(parent, -1)
self.AddLabelTool(wx.ID_SAVE, "Record", wx.Bitmap("picture.png", wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, "", "")
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title)
self.toolbar = Toolbar(self)
self.SetToolBar(self.toolbar)
self.toolbar.Realize()
self.panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
self.panel1 = PanelWithDrawing(self.panel)
vbox.Add(self.panel1)
# self.panel2 = PanelWithText(self.panel)
# vbox.Add(self.panel2)
self.panel.SetSizer(vbox)
self.Centre()
self.Show()
self.toolbar.Bind(wx.EVT_TOOL, self.onButton)
self.panel1.Bind(wx.EVT_ERASE_BACKGROUND, self.onErase)
def onErase(self, evt):
try:
dc = evt.GetDC()
except:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
self.panel1.onErase(dc)
def onButton(self, evt):
self.panel1.showbmp = not self.panel1.showbmp
wx.PostEvent(self.panel1, wx.PyCommandEvent(wx.wxEVT_ERASE_BACKGROUND))
if __name__ == '__main__':
app = wx.App()
Example(None, title='Example')
wx.lib.inspection.InspectionTool().Show() # use this for debugging GUI design
app.MainLoop()
How do I tell wxpython to draw all the non-background stuff again? Alternatively, how do I not un-draw it in the first place?
After working on it for a few days, I got it! And the answer is trivially simple (as usual).
wx.PostEvent(self.panel1, wx.PyCommandEvent(wx.wxEVT_ERASE_BACKGROUND)) should be replaced with self.Refresh() to refresh the whole frame and not just force a specific (and apparently unsafe) redraw.