How to create a customized frame - Part 6 (Phoenix)

Keywords : Shaped frame, Customized frame, Customized button, Transparency, Roll, Unroll, Fade in, Fade out, Shape, Region, BufferedPaintDC, BufferedDC, ClientDC, GCDC, AutoBufferedPaintDCFactory, Alpha, Config, AcceleratorTable.


Demonstrating (only Windows) :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

Test, modify, correct, complete, improve and share your discoveries ! (!)


Shaped frame with alpha :

Thank you so much to Kevin Schlosser and Metallicow for the "Alpha" source code.

ShapedWindow with Alpha that works on wxPy4.0 and 4.1.

I like it ! (Ecco ;) ).

First example

img_sample_one.png

   1 # sample_one.py
   2 
   3 import sys
   4 import os
   5 import platform
   6 import time
   7 import wx
   8 import wx.adv
   9 import wx.lib.fancytext as fancytext
  10 try:
  11     from wx.lib.mswalpha import draw_alpha
  12 except ImportError:
  13     from mswalpha import draw_alpha
  14 import rectshapedbitmapbuttonTwo as SBBTwo
  15 
  16 # class MyAboutDlg
  17 # class MyFirstFrame
  18 # class MySecondFrame
  19 # class MyApp
  20 
  21 #-------------------------------------------------------------------------------
  22 
  23 class MyAboutDlg(wx.Dialog):
  24     """
  25     ...
  26     """
  27     def __init__(self, parent):
  28         style = (wx.FRAME_SHAPED | wx.SIMPLE_BORDER |
  29                  wx.CLIP_CHILDREN | wx.STAY_ON_TOP |
  30                  wx.SYSTEM_MENU | wx.CLOSE_BOX |
  31                  wx.NO_FULL_REPAINT_ON_RESIZE)
  32         wx.Dialog.__init__(self,
  33                           parent,
  34                           id=-1,
  35                           title="About...",
  36                           style=style)
  37 
  38         #------------
  39 
  40         # Attributes.
  41         self.SetTransparent(0)
  42         self.opacity_in = 0
  43         self.opacity_out = 255
  44         self.deltaN = -70
  45         self.hasShape = False
  46         self.delta = wx.Point(0,0)
  47 
  48         #------------
  49 
  50         # Return application name.
  51         self.app_name = wx.GetApp().GetAppName()
  52         # Return bitmaps folder.
  53         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
  54         # Return icons folder.
  55         self.icons_dir = wx.GetApp().GetIconsDir()
  56 
  57         #------------
  58 
  59         # Simplified init method.
  60         self.SetProperties()
  61         self.OnTimerIn(self)
  62         self.CreateCtrls()
  63         self.BindEvents()
  64 
  65         #------------
  66 
  67         self.CenterOnParent(wx.BOTH)
  68 
  69         #------------
  70 
  71         self.ShowModal()
  72         self.Destroy()
  73 
  74     #---------------------------------------------------------------------------
  75 
  76     def SetProperties(self):
  77         """
  78         Set the dialog properties (title, icon, transparency...).
  79         """
  80 
  81         frameIcon = wx.Icon(os.path.join(self.icons_dir,
  82                                          "icon_wx.ico"),
  83                             type=wx.BITMAP_TYPE_ICO)
  84         self.SetIcon(frameIcon)
  85 
  86 
  87     def OnTimerIn(self, evt):
  88         """
  89         Thanks to Pascal Faut.
  90         """
  91 
  92         self.timer1 = wx.Timer(self, -1)
  93         self.timer1.Start(1)
  94         self.Bind(wx.EVT_TIMER, self.AlphaCycle1, self.timer1)
  95 
  96         print("Fade-in was launched.")
  97 
  98 
  99     def OnTimerOut(self, evt):
 100         """
 101         Thanks to Pascal Faut.
 102         """
 103 
 104         self.timer2 = wx.Timer(self, -1)
 105         self.timer2.Start(1)
 106         self.Bind(wx.EVT_TIMER, self.AlphaCycle2, self.timer2)
 107 
 108         print("Fade-out was launched.")
 109 
 110 
 111     def AlphaCycle1(self, *args):
 112         """
 113         Thanks to Pascal Faut.
 114         """
 115 
 116         self.opacity_in += self.deltaN
 117         if self.opacity_in <= 0:
 118             self.deltaN = -self.deltaN
 119             self.opacity_in = 0
 120 
 121         if self.opacity_in >= 255:
 122             self.deltaN = -self.deltaN
 123             self.opacity_in = 255
 124 
 125             self.timer1.Stop()
 126 
 127         self.SetTransparent(self.opacity_in)
 128 
 129         print("Fade in = {}/255".format(self.opacity_in))
 130 
 131 
 132     def AlphaCycle2(self, *args):
 133         """
 134         Thanks to Pascal Faut.
 135         """
 136 
 137         self.opacity_out += self.deltaN
 138         if self.opacity_out >= 255:
 139             self.deltaN = -self.deltaN
 140             self.opacity_out = 255
 141 
 142         if self.opacity_out <= 0:
 143             self.deltaN = -self.deltaN
 144             self.opacity_out = 0
 145 
 146             self.timer2.Stop()
 147 
 148             wx.CallAfter(self.Destroy)
 149 
 150         self.SetTransparent(self.opacity_out)
 151 
 152         print("Fade out = {}/255".format(self.opacity_out))
 153 
 154 
 155     def CreateCtrls(self):
 156         """
 157         Make widgets for my dialog.
 158         """
 159 
 160         # Load a background bitmap.
 161         self.bmp = wx.Bitmap(os.path.join(self.bitmaps_dir,
 162                                           "skin_about_2.png"),
 163                              type=wx.BITMAP_TYPE_PNG)
 164         mask = wx.Mask(self.bmp, wx.RED)
 165         self.bmp.SetMask(mask)
 166 
 167         #------------
 168 
 169         self.SetClientSize((self.bmp.GetWidth(), self.bmp.GetHeight()))
 170 
 171         #------------
 172 
 173         if wx.Platform == "__WXGTK__":
 174             # wxGTK requires that the window be created before you can
 175             # set its shape, so delay the call to SetWindowShape until
 176             # this event.
 177             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 178         else:
 179             # On wxMSW and wxMac the window has already
 180             # been created, so go for it.
 181             self.SetWindowShape()
 182 
 183 
 184     def BindEvents(self):
 185         """
 186         Bind all the events related to my dialog.
 187         """
 188 
 189         # Bind some events to an events handler.
 190         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 191         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 192         self.Bind(wx.EVT_RIGHT_UP, self.OnCloseWindow)  # Panel right clic.
 193         self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)  # View mask.
 194         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
 195         self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 196         self.Bind(wx.EVT_MOTION, self.OnMouseMove)
 197         self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
 198         self.Bind(wx.EVT_PAINT, self.OnPaint)
 199         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 200 
 201 
 202     def SetWindowShape(self, event=None):
 203         """
 204         ...
 205         """
 206 
 207         # Use the bitmap's mask to determine the region.
 208         r = wx.Region(self.bmp)
 209         self.hasShape = self.SetShape(r)
 210 
 211 
 212     def OnEraseBackground(self, event):
 213         """
 214         ...
 215         """
 216 
 217         dc = event.GetDC()
 218         if not dc:
 219             dc = wx.ClientDC(self)
 220             rect = self.GetUpdateRegion().GetBox()
 221             dc.SetClippingRect(rect)
 222 
 223 
 224     def OnDoubleClick(self, event):
 225         """
 226         ...
 227         """
 228 
 229         if self.hasShape:
 230             self.SetShape(wx.Region())
 231             self.hasShape = False
 232         else:
 233             self.SetWindowShape()
 234 
 235 
 236     def OnLeftDown(self, event):
 237         """
 238         ...
 239         """
 240 
 241         self.CaptureMouse()
 242         x, y = self.ClientToScreen(event.GetPosition())
 243         originx, originy = self.GetPosition()
 244         dx = x - originx
 245         dy = y - originy
 246         self.delta = ((dx, dy))
 247 
 248 
 249     def OnLeftUp(self, evt):
 250         """
 251         ...
 252         """
 253 
 254         if self.HasCapture():
 255             self.ReleaseMouse()
 256 
 257 
 258     def OnMouseMove(self, event):
 259         """
 260         ...
 261         """
 262 
 263         if event.Dragging() and event.LeftIsDown():
 264             x, y = self.ClientToScreen(event.GetPosition())
 265             fp = (x - self.delta[0], y - self.delta[1])
 266             self.Move(fp)
 267 
 268 
 269     def OnPaint(self, event):
 270         """
 271         ...
 272         """
 273 
 274         dc = wx.AutoBufferedPaintDCFactory(self)
 275         dc.DrawBitmap(self.bmp, -1, -1, True)
 276 
 277         #------------
 278 
 279         # These are strings.
 280         py_version = sys.version.split()[0]
 281 
 282         str1 = (('<font style="normal" family="default" color="yellow" size="10" weight="bold">'
 283                  'Programming : </font>'
 284                  '<font style="normal" family="default" color="black" size="10" weight="normal">'
 285                  'Python {}</font>').format(py_version))   # Python 3.6.5
 286 
 287         str2 = (('<font style="normal" family="default" color="red" size="10" weight="bold">'
 288                  'GUI toolkit : </font>'
 289                  '<font style="normal" family="default" color="black" size="10" weight="normal">'
 290                  'wxPython {}</font>').format(wx.VERSION_STRING))  # wxPython 4.0.2
 291 
 292         str3 = (('<font style="normal" family="default" color="brown" size="10" weight="bold">'
 293                  'Library : </font>'
 294                  '<font style="normal" family="default" color="black" size="10" weight="normal">'
 295                  '{}</font>').format(wx.GetLibraryVersionInfo().VersionString))   # wxWidgets 3.0.5
 296 
 297         str4 = (('<font style="normal" family="default" color="blue" size="10" weight="bold">'
 298                  'Operating system : </font>'
 299                  '<font style="normal" family="default" color="black" size="10" weight="normal">'
 300                  '{}</font>').format(platform.system()))   # Windows
 301 
 302         str5 = (('<font style="normal" family="default" color="gray" size="9" weight="normal">'
 303                  '{}</font>').format(self.app_name))   # Custom Gui 1
 304 
 305         str6 = (('<font style="normal" family="default" color="black" size="8" weight="normal">'
 306                  'Right clic or Esc for Exit</font>'))
 307 
 308         #------------
 309 
 310         # Return main image size.
 311         bw, bh = self.bmp.GetWidth(), self.bmp.GetHeight()
 312 
 313         # Draw text.
 314         # Need width to calculate x position of str1.
 315         tw, th = fancytext.GetExtent(str1, dc)
 316         # Centered text.
 317         fancytext.RenderToDC(str1, dc, (bw-tw)/2, 20)
 318 
 319         #------------
 320 
 321         # Need width to calculate x position of str2.
 322         tw, th = fancytext.GetExtent(str2, dc)
 323         # Centered text.
 324         fancytext.RenderToDC(str2, dc, (bw-tw)/2, 40)
 325 
 326         #------------
 327 
 328         # Need width to calculate x position of str3.
 329         tw, th = fancytext.GetExtent(str3, dc)
 330         # Centered text.
 331         fancytext.RenderToDC(str3, dc, (bw-tw)/2, 60)
 332 
 333         #------------
 334 
 335         # Need width to calculate x position of str4.
 336         tw, th = fancytext.GetExtent(str4, dc)
 337         # Centered text.
 338         fancytext.RenderToDC(str4, dc, (bw-tw)/2, 90)
 339 
 340         #------------
 341 
 342         # Need width to calculate x position of str5.
 343         tw, th = fancytext.GetExtent(str5, dc)
 344         # Centered text.
 345         fancytext.RenderToDC(str5, dc, (bw-tw)/2, 120)
 346 
 347         #------------
 348 
 349         # Need width to calculate x position of str6.
 350         tw, th = fancytext.GetExtent(str6, dc)
 351         # Centered text.
 352         fancytext.RenderToDC(str6, dc, (bw-tw)/2, 155)
 353 
 354 
 355     def OnKeyUp(self, event):
 356         """
 357         ...
 358         """
 359 
 360         if event.GetKeyCode() == wx.WXK_ESCAPE:
 361             self.OnCloseWindow(event)
 362 
 363         event.Skip()
 364 
 365 
 366     def OnCloseWindow(self, event):
 367         """
 368         ...
 369         """
 370 
 371         #self.Destroy()
 372         self.OnTimerOut(self)
 373 
 374 #-------------------------------------------------------------------------------
 375 
 376 class MyFirstFrame(wx.Frame):
 377     """
 378     ...
 379     """
 380     style = (wx.CLIP_CHILDREN | wx.CLOSE_BOX |
 381              wx.MINIMIZE_BOX | wx.SYSTEM_MENU |
 382              wx.NO_BORDER | wx.FRAME_SHAPED | # wx.FRAME_NO_TASKBAR
 383              wx.NO_FULL_REPAINT_ON_RESIZE | wx.STAY_ON_TOP)
 384     def __init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString,
 385                  pos=wx.DefaultPosition, size=wx.DefaultSize,
 386                  style=style,
 387                  name='frame'):
 388         wx.Frame.__init__(self, parent, id, title, pos, size, style, name)
 389 
 390         #------------
 391 
 392         # Attributes.
 393         self.delta = wx.Point(0,0)
 394 
 395         #------------
 396 
 397         # Return application name.
 398         self.app_name = wx.GetApp().GetAppName()
 399         # Return bitmaps folder.
 400         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
 401         # Return icons folder.
 402         self.icons_dir = wx.GetApp().GetIconsDir()
 403 
 404         #------------
 405 
 406         # Create a timer.
 407         self.timer = wx.Timer(self)
 408         self.timer.Start(1000)
 409         self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
 410 
 411         #------------
 412 
 413         # Simplified init method.
 414         self.SetProperties()
 415         self.CreateCtrls()
 416         self.BindEvents()
 417 
 418         #------------
 419 
 420         self.CenterOnScreen(wx.BOTH)
 421 
 422     #---------------------------------------------------------------------------
 423 
 424     def SetProperties(self):
 425         """
 426         ...
 427         """
 428 
 429         self.SetTitle(self.app_name)
 430         self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 431 
 432         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 433                                          "icon_wx.ico"),
 434                             type=wx.BITMAP_TYPE_ICO)
 435         self.SetIcon(frameIcon)
 436 
 437 
 438     def CreateCtrls(self):
 439         """
 440         ...
 441         """
 442 
 443         # Load a background bitmap.
 444         self.bitmap = wx.Bitmap(os.path.join(self.bitmaps_dir,
 445                                              "clouds.png"),
 446                                 type=wx.BITMAP_TYPE_PNG)
 447         # or
 448         # image = wx.Image('phone.png', wx.BITMAP_TYPE_PNG)
 449         # blurimage = image.Blur(1)
 450         # self.bitmap = blurimage.ConvertToBitmap()
 451 
 452         self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))
 453 
 454         #------------
 455 
 456         if wx.Platform == "__WXGTK__":
 457             # wxGTK requires that the window be created before you can
 458             # set its shape, so delay the call to SetWindowShape until
 459             # this event.
 460             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 461         else:
 462             # On wxMSW and wxMac the window has
 463             # already been created, so go for it.
 464             self.SetWindowShape()
 465 
 466         #------------
 467 
 468         tt = wx.ToolTip('LeftClick to Drag - RightClick to Close')
 469         self.SetToolTip(tt)
 470 
 471         #------------
 472 
 473         # It appears that we cannot make child widgets on the Frame
 474         # when using mswalpha, there fore we will make a "child" shaped
 475         # frame that will handle widgets transparency also.
 476         # self.button = wx.Button(self, -1, 'Button', pos=(100, 100))
 477 
 478         #------------
 479 
 480         self.Centre()
 481         self.widgetsframe = MySecondFrame(self,
 482                                           pos=self.GetPosition(),
 483                                           size=self.GetSize())
 484         self.widgetsframe.Show()
 485 
 486         #------------
 487 
 488         # Create an accelerator table.
 489         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('X'),
 490                                                wx.ID_EXIT),
 491                                               (wx.ACCEL_CTRL, ord('A'),
 492                                                wx.ID_ABOUT)
 493                                              ])
 494         self.SetAcceleratorTable(self.accel_tbl)
 495 
 496 
 497     def BindEvents(self):
 498         """
 499         Bind some events to an events handle.
 500         """
 501 
 502         self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
 503         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
 504 
 505         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
 506         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 507         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 508         self.Bind(wx.EVT_MOTION, self.OnMouseMove)
 509         self.Bind(wx.EVT_RIGHT_UP, self.OnExit)
 510         self.Bind(wx.EVT_PAINT, self.OnPaint)
 511 
 512 
 513     def SetWindowShape(self, *event):
 514         """
 515         ...
 516         """
 517 
 518         # Use the bitmap's mask to determine the region.
 519         self.region = wx.Region(self.bitmap)
 520         self.hasShape = self.SetShape(self.region)
 521 
 522 
 523     def OnLeftDown(self, event):
 524         """
 525         ...
 526         """
 527 
 528         if self.HasCapture():
 529             self.ReleaseMouse()
 530 
 531         self.CaptureMouse()
 532         x, y = self.ClientToScreen(event.GetPosition())
 533         originx, originy = self.GetPosition()
 534         dx = x - originx
 535         dy = y - originy
 536         self.delta = (dx, dy)
 537 
 538 
 539     def OnLeftUp(self, event):
 540         """
 541         ...
 542         """
 543 
 544         if self.HasCapture():
 545             self.ReleaseMouse()
 546 
 547 
 548     def OnMouseMove(self, event):
 549         """
 550         ...
 551         """
 552 
 553         if event.Dragging() and event.LeftIsDown():
 554             x, y = self.ClientToScreen(event.GetPosition())
 555             fp = (x - self.delta[0], y - self.delta[1])
 556             self.SetPosition(fp)
 557             self.widgetsframe.SetPosition(fp)
 558 
 559 
 560     def Draw(self):
 561         """
 562         ...
 563         """
 564 
 565         # Return client size.
 566         width, height = self.GetClientSize()
 567 
 568         # Return main image size.
 569         bw, bh = self.bitmap.GetWidth(), self.bitmap.GetHeight()
 570 
 571         #------------
 572 
 573         dc = wx.MemoryDC()
 574 
 575         #------------
 576 
 577         fontSize = self.GetFont().GetPointSize()
 578 
 579         # wx.Font(pointSize, family, style, weight, underline, faceName)
 580         if wx.Platform == "__WXGTK__":
 581             self.normalBoldFont = wx.Font(fontSize-1,
 582                                           wx.DEFAULT, wx.NORMAL,
 583                                           wx.NORMAL, False, "")
 584             self.normalFont = wx.Font(fontSize-2,
 585                                       wx.DEFAULT, wx.NORMAL,
 586                                       wx.NORMAL, False, "")
 587 
 588         else:
 589             self.normalBoldFont = wx.Font(fontSize+23,
 590                                           wx.DEFAULT, wx.NORMAL,
 591                                           wx.NORMAL, False, "")
 592             self.normalFont = wx.Font(fontSize+1,
 593                                       wx.DEFAULT, wx.NORMAL,
 594                                       wx.NORMAL, False, "")
 595 
 596         dc.SetFont(self.normalFont)
 597         dc.SetFont(self.normalBoldFont)
 598 
 599         #------------
 600 
 601         bmp = wx.Bitmap.FromRGBA(width, height, red=0, green=0, blue=0, alpha=0)
 602         dc.SelectObject(bmp)
 603 
 604         #------------
 605 
 606         gc = wx.GraphicsContext.Create(dc)
 607         gcdc = wx.GCDC(gc)
 608 
 609         # Draw a bitmap with an alpha channel
 610         # on top of the last group.
 611         # image, x, y, transparence
 612         gcdc.DrawBitmap(self.bitmap, -1, -1, useMask=False)
 613 
 614         # Draw text.
 615         gcdc.SetTextForeground(wx.Colour(250, 250, 250, 255))  # grey
 616         gcdc.SetTextBackground(wx.TransparentColour)
 617         gcdc.SetFont(self.normalFont)
 618         date = time.strftime("%A %d %B %Y")
 619         tw, th = gcdc.GetTextExtent(date)
 620         gcdc.DrawText(date, (int((bw-tw)/2), int(133)))
 621 
 622         gcdc.SetTextForeground(wx.Colour(95, 95, 95, 255))  # white
 623         gcdc.SetTextBackground(wx.TransparentColour)
 624         gcdc.SetFont(self.normalBoldFont)
 625         hour = time.strftime("%H:%M:%S")  # "%I:%M:%S %p"
 626         tw, th = gcdc.GetTextExtent(hour)
 627         gcdc.DrawText(hour, (int((bw-tw)/2-5), int(90)))
 628 
 629         #------------
 630 
 631         gcdc.Destroy()
 632         del gcdc
 633 
 634         dc.Destroy()
 635         del dc
 636 
 637         #------------
 638 
 639         draw_alpha(self, bmp)
 640 
 641 
 642     def OnTimer(self, event):
 643         """
 644         ...
 645         """
 646 
 647         dc = wx.BufferedDC(wx.ClientDC(self))
 648         dc.Clear()
 649 
 650         self.Draw()
 651 
 652 
 653     def OnPaint(self, event):
 654         """
 655         ...
 656         """
 657 
 658         dc = wx.BufferedPaintDC(self)
 659         dc.Clear()
 660 
 661         self.Draw()
 662 
 663 
 664     def OnAbout(self, event):
 665         """
 666         ...
 667         """
 668 
 669         self.dialog = MyAboutDlg(self)
 670 
 671 
 672     def OnExit(self, event):
 673         """
 674         ...
 675         """
 676 
 677         self.widgetsframe.Close()
 678         self.Close()
 679 
 680 #-------------------------------------------------------------------------------
 681 
 682 class MySecondFrame(wx.Frame):
 683     """
 684     ...
 685     """
 686     def __init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString,
 687                  pos=wx.DefaultPosition, size=wx.DefaultSize,
 688                  style=wx.FRAME_SHAPED |
 689                        wx.NO_BORDER |
 690                        wx.FRAME_NO_TASKBAR |
 691                        wx.FRAME_FLOAT_ON_PARENT,
 692                  name="frame"):
 693         wx.Frame.__init__(self, parent, id, title, pos, size, style, name)
 694 
 695         #------------
 696 
 697         # Attributes.
 698         self.SetTransparent(255)
 699 
 700         #------------
 701 
 702         # Return bitmaps folder.
 703         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
 704         # Return icons folder.
 705         self.icons_dir = wx.GetApp().GetIconsDir()
 706 
 707         #------------
 708 
 709         # Simplified init method.
 710         self.SetProperties()
 711         self.CreateCtrls()
 712         self.BindEvents()
 713 
 714     #---------------------------------------------------------------------------
 715 
 716     def SetProperties(self):
 717         """
 718         ...
 719         """
 720 
 721         self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 722 
 723 
 724     def CreateCtrls(self):
 725         """
 726         ...
 727         """
 728 
 729         self.slider = wx.Slider(self, -1,
 730                                 value=160,
 731                                 minValue=64,
 732                                 maxValue=255,
 733                                 size=(0, 0),
 734                                 pos=(195, 20),
 735                                 style=wx.SL_HORIZONTAL)
 736         self.slider.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 737 
 738         #------------
 739 
 740         # Button About.
 741         self.btn1 = SBBTwo.ShapedBitmapButton(self, -1,
 742             bitmap=wx.Bitmap(os.path.join(self.bitmaps_dir,
 743                                           "btn_about_normal1.png"),
 744                              type=wx.BITMAP_TYPE_PNG),
 745 
 746             pressedBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 747                                               "btn_about_pressed1.png"),
 748                                  type=wx.BITMAP_TYPE_PNG),
 749 
 750             hoverBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 751                                             "btn_about_normal1.png"),
 752                                type=wx.BITMAP_TYPE_PNG),
 753 
 754             disabledBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 755                                                "btn_about_disabled1.png"),
 756                                   type=wx.BITMAP_TYPE_PNG),
 757 
 758             label="",
 759             labelForeColour=wx.WHITE,
 760             labelFont=wx.Font(9,
 761                               wx.FONTFAMILY_DEFAULT,
 762                               wx.FONTSTYLE_NORMAL,
 763                               wx.FONTWEIGHT_BOLD),
 764             style=wx.BORDER_NONE)
 765 
 766         self.btn1.SetPosition((int((169)), int(19)))
 767         self.btn1.SetSize((15, 15))
 768 
 769         #------------
 770 
 771         if wx.Platform == "__WXGTK__":
 772             # wxGTK requires that the window be created before you can
 773             # set its shape, so delay the call to SetWindowShape until
 774             # this event.
 775             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 776         else:
 777             # On wxMSW and wxMac the window has
 778             # already been created, so go for it.
 779             self.SetWindowShape()
 780 
 781 
 782     def BindEvents(self):
 783         """
 784         Bind some events to an events handler.
 785         """
 786 
 787         self.slider.Bind(wx.EVT_SLIDER, self.OnSlider)
 788         self.btn1.Bind(wx.EVT_BUTTON, self.OnBtnAbout)
 789 
 790         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 791         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 792 
 793 
 794     def SetWindowShape(self, *event):
 795         """
 796         ...
 797         """
 798 
 799         # Use the widget's rect's to determine the region.
 800         wxRegion = wx.Region
 801         self.region = wxRegion()
 802         widgets = [child for child in self.GetChildren()]
 803         regions = [wxRegion(widget.GetRect()) for widget in widgets]
 804         Union = self.region.Union
 805         [Union(reg) for reg in regions]
 806         self.hasShape = self.SetShape(self.region)
 807 
 808 
 809     def OnLeftDown(self, event):
 810         """
 811         ...
 812         """
 813 
 814         if self.HasCapture():
 815             self.ReleaseMouse()
 816 
 817         self.CaptureMouse()
 818         x, y = self.ClientToScreen(event.GetPosition())
 819         originx, originy = self.GetPosition()
 820         dx = x - originx
 821         dy = y - originy
 822         self.delta = (dx, dy)
 823 
 824 
 825     def OnLeftUp(self, event):
 826         """
 827         ...
 828         """
 829 
 830         if self.HasCapture():
 831             self.ReleaseMouse()
 832 
 833 
 834     def OnBtnAbout(self, event):
 835         """
 836         ...
 837         """
 838 
 839         self.GetParent().OnAbout(self)
 840 
 841 
 842     def OnBtnClose(self, event):
 843         """
 844         ...
 845         """
 846 
 847         self.GetParent().OnExit(self)
 848 
 849         print("Close button was clicked.")
 850 
 851 
 852     def OnSlider(self, event):
 853         """
 854         ...
 855         """
 856 
 857         self.SetTransparent(event.GetEventObject().GetValue())
 858 
 859 #-------------------------------------------------------------------------------
 860 
 861 class MyApp(wx.App):
 862     """
 863     Thanks to Andrea Gavana.
 864     """
 865     def OnInit(self):
 866 
 867         #------------
 868 
 869         self.locale = wx.Locale(wx.LANGUAGE_FRENCH)
 870 
 871         #------------
 872 
 873         self.SetAppName("Custom Gui 1")
 874 
 875         #------------
 876 
 877         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 878 
 879         #------------
 880 
 881         frame = MyFirstFrame(None)
 882         self.SetTopWindow(frame)
 883         frame.Show(True)
 884 
 885         return True
 886 
 887     #---------------------------------------------------------------------------
 888 
 889     def GetInstallDir(self):
 890         """
 891         Returns the installation directory for my application.
 892         """
 893 
 894         return self.installDir
 895 
 896 
 897     def GetIconsDir(self):
 898         """
 899         Returns the icons directory for my application.
 900         """
 901 
 902         icons_dir = os.path.join(self.installDir, "icons")
 903         return icons_dir
 904 
 905 
 906     def GetBitmapsDir(self):
 907         """
 908         Returns the bitmaps directory for my application.
 909         """
 910 
 911         bitmaps_dir = os.path.join(self.installDir, "bitmaps")
 912         return bitmaps_dir
 913 
 914 #-------------------------------------------------------------------------------
 915 
 916 def main():
 917     app = MyApp(False)
 918     app.MainLoop()
 919 
 920 #-------------------------------------------------------------------------------
 921 
 922 if __name__ == "__main__" :
 923     wxVER = 'wxPython %s' % wx.version()
 924     pyVER = 'python %d.%d.%d.%s' % sys.version_info[0:4]
 925     versionInfos = '%s %s' % (wxVER, pyVER)
 926     print(versionInfos)
 927     main()


Second example

img_sample_two.png

   1 # sample_two.py
   2 
   3 import sys
   4 import os
   5 import platform
   6 import time
   7 import wx
   8 import wx.adv
   9 import wx.lib.fancytext as fancytext
  10 try:
  11     from wx.lib.mswalpha import draw_alpha
  12 except ImportError:
  13     from mswalpha import draw_alpha
  14 import rectshapedbitmapbuttonTwo as SBBTwo
  15 
  16 # class MyAboutDlg
  17 # class MyFirstFrame
  18 # class MySecondFrame
  19 # class MyApp
  20 
  21 #-------------------------------------------------------------------------------
  22 
  23 class MyAboutDlg(wx.Dialog):
  24     """
  25     ...
  26     """
  27     def __init__(self, parent):
  28         style = (wx.FRAME_SHAPED | wx.SIMPLE_BORDER |
  29                  wx.CLIP_CHILDREN | wx.STAY_ON_TOP |
  30                  wx.SYSTEM_MENU | wx.CLOSE_BOX |
  31                  wx.NO_FULL_REPAINT_ON_RESIZE)
  32         wx.Dialog.__init__(self,
  33                           parent,
  34                           id=-1,
  35                           title="About...",
  36                           style=style)
  37 
  38         #------------
  39 
  40         # Attributes.
  41         self.SetTransparent(0)
  42         self.opacity_in = 0
  43         self.opacity_out = 230
  44         self.deltaN = -70
  45         self.hasShape = False
  46         self.delta = wx.Point(0,0)
  47 
  48         #------------
  49 
  50         # Return application name.
  51         self.app_name = wx.GetApp().GetAppName()
  52         # Return bitmaps folder.
  53         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
  54         # Return icons folder.
  55         self.icons_dir = wx.GetApp().GetIconsDir()
  56 
  57         #------------
  58 
  59         # Simplified init method.
  60         self.SetProperties()
  61         self.OnTimerIn(self)
  62         self.CreateCtrls()
  63         self.BindEvents()
  64 
  65         #------------
  66 
  67         self.CenterOnParent(wx.BOTH)
  68 
  69         #------------
  70 
  71         self.ShowModal()
  72         self.Destroy()
  73 
  74     #---------------------------------------------------------------------------
  75 
  76     def SetProperties(self):
  77         """
  78         Set the dialog properties (title, icon, transparency...).
  79         """
  80 
  81         frameIcon = wx.Icon(os.path.join(self.icons_dir,
  82                                          "icon_wx.ico"),
  83                             type=wx.BITMAP_TYPE_ICO)
  84         self.SetIcon(frameIcon)
  85 
  86 
  87     def OnTimerIn(self, evt):
  88         """
  89         Thanks to Pascal Faut.
  90         """
  91 
  92         self.timer1 = wx.Timer(self, -1)
  93         self.timer1.Start(1)
  94         self.Bind(wx.EVT_TIMER, self.AlphaCycle1, self.timer1)
  95 
  96         print("Fade-in was launched.")
  97 
  98 
  99     def OnTimerOut(self, evt):
 100         """
 101         Thanks to Pascal Faut.
 102         """
 103 
 104         self.timer2 = wx.Timer(self, -1)
 105         self.timer2.Start(1)
 106         self.Bind(wx.EVT_TIMER, self.AlphaCycle2, self.timer2)
 107 
 108         print("Fade-out was launched.")
 109 
 110 
 111     def AlphaCycle1(self, *args):
 112         """
 113         Thanks to Pascal Faut.
 114         """
 115 
 116         self.opacity_in += self.deltaN
 117         if self.opacity_in <= 0:
 118             self.deltaN = -self.deltaN
 119             self.opacity_in = 0
 120 
 121         if self.opacity_in >= 230:
 122             self.deltaN = -self.deltaN
 123             self.opacity_in = 230
 124 
 125             self.timer1.Stop()
 126 
 127         self.SetTransparent(self.opacity_in)
 128 
 129         print("Fade in = {}/255".format(self.opacity_in))
 130 
 131 
 132     def AlphaCycle2(self, *args):
 133         """
 134         Thanks to Pascal Faut.
 135         """
 136 
 137         self.opacity_out += self.deltaN
 138         if self.opacity_out >= 230:
 139             self.deltaN = -self.deltaN
 140             self.opacity_out = 230
 141 
 142         if self.opacity_out <= 0:
 143             self.deltaN = -self.deltaN
 144             self.opacity_out = 0
 145 
 146             self.timer2.Stop()
 147 
 148             wx.CallAfter(self.Destroy)
 149 
 150         self.SetTransparent(self.opacity_out)
 151 
 152         print("Fade out = {}/255".format(self.opacity_out))
 153 
 154 
 155     def CreateCtrls(self):
 156         """
 157         Make widgets for my dialog.
 158         """
 159 
 160         # Load a background bitmap.
 161         self.bmp = wx.Bitmap(os.path.join(self.bitmaps_dir,
 162                                           "skin_about_1.png"),
 163                              type=wx.BITMAP_TYPE_PNG)
 164         mask = wx.Mask(self.bmp, wx.RED)
 165         self.bmp.SetMask(mask)
 166 
 167         #------------
 168 
 169         self.SetClientSize((self.bmp.GetWidth(), self.bmp.GetHeight()))
 170 
 171         #------------
 172 
 173         if wx.Platform == "__WXGTK__":
 174             # wxGTK requires that the window be created before you can
 175             # set its shape, so delay the call to SetWindowShape until
 176             # this event.
 177             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 178         else:
 179             # On wxMSW and wxMac the window has already
 180             # been created, so go for it.
 181             self.SetWindowShape()
 182 
 183 
 184     def BindEvents(self):
 185         """
 186         Bind all the events related to my dialog.
 187         """
 188 
 189         # Bind some events to an events handler.
 190         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 191         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 192         self.Bind(wx.EVT_RIGHT_UP, self.OnCloseWindow)  # Panel right clic.
 193         self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)  # View mask.
 194         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
 195         self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 196         self.Bind(wx.EVT_MOTION, self.OnMouseMove)
 197         self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
 198         self.Bind(wx.EVT_PAINT, self.OnPaint)
 199         self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
 200 
 201 
 202     def SetWindowShape(self, event=None):
 203         """
 204         ...
 205         """
 206 
 207         # Use the bitmap's mask to determine the region.
 208         r = wx.Region(self.bmp)
 209         self.hasShape = self.SetShape(r)
 210 
 211 
 212     def OnEraseBackground(self, event):
 213         """
 214         ...
 215         """
 216 
 217         dc = event.GetDC()
 218         if not dc:
 219             dc = wx.ClientDC(self)
 220             rect = self.GetUpdateRegion().GetBox()
 221             dc.SetClippingRect(rect)
 222 
 223 
 224     def OnDoubleClick(self, event):
 225         """
 226         ...
 227         """
 228 
 229         if self.hasShape:
 230             self.SetShape(wx.Region())
 231             self.hasShape = False
 232         else:
 233             self.SetWindowShape()
 234 
 235 
 236     def OnLeftDown(self, event):
 237         """
 238         ...
 239         """
 240 
 241         self.CaptureMouse()
 242         x, y = self.ClientToScreen(event.GetPosition())
 243         originx, originy = self.GetPosition()
 244         dx = x - originx
 245         dy = y - originy
 246         self.delta = ((dx, dy))
 247 
 248 
 249     def OnLeftUp(self, evt):
 250         """
 251         ...
 252         """
 253 
 254         if self.HasCapture():
 255             self.ReleaseMouse()
 256 
 257 
 258     def OnMouseMove(self, event):
 259         """
 260         ...
 261         """
 262 
 263         if event.Dragging() and event.LeftIsDown():
 264             x, y = self.ClientToScreen(event.GetPosition())
 265             fp = (x - self.delta[0], y - self.delta[1])
 266             self.Move(fp)
 267 
 268 
 269     def OnPaint(self, event):
 270         """
 271         ...
 272         """
 273 
 274         dc = wx.AutoBufferedPaintDCFactory(self)
 275         dc.DrawBitmap(self.bmp, -1, -1, True)
 276 
 277         #------------
 278 
 279         # These are strings.
 280         py_version = sys.version.split()[0]
 281 
 282         str1 = (('<font style="normal" family="default" color="yellow" size="10" weight="bold">'
 283                  'Programming : </font>'
 284                  '<font style="normal" family="default" color="white" size="10" weight="normal">'
 285                  'Python {}</font>').format(py_version))   # Python 3.6.5
 286 
 287         str2 = (('<font style="normal" family="default" color="red" size="10" weight="bold">'
 288                  'GUI toolkit : </font>'
 289                  '<font style="normal" family="default" color="white" size="10" weight="normal">'
 290                  'wxPython {}</font>').format(wx.VERSION_STRING))  # wxPython 4.0.2
 291 
 292         str3 = (('<font style="normal" family="default" color="brown" size="10" weight="bold">'
 293                  'Library : </font>'
 294                  '<font style="normal" family="default" color="white" size="10" weight="normal">'
 295                  '{}</font>').format(wx.GetLibraryVersionInfo().VersionString))   # wxWidgets 3.0.5
 296 
 297         str4 = (('<font style="normal" family="default" color="cyan" size="10" weight="bold">'
 298                  'Operating system : </font>'
 299                  '<font style="normal" family="default" color="white" size="10" weight="normal">'
 300                  '{}</font>').format(platform.system()))   # Windows
 301 
 302         str5 = (('<font style="normal" family="default" color="gray" size="9" weight="normal">'
 303                  '{}</font>').format(self.app_name))   # Custom Gui 1
 304 
 305         str6 = (('<font style="normal" family="default" color="White" size="8" weight="normal">'
 306                  'Right clic or Esc for Exit</font>'))
 307 
 308         #------------
 309 
 310         # Return main image size.
 311         bw, bh = self.bmp.GetWidth(), self.bmp.GetHeight()
 312 
 313         # Draw text.
 314         # Need width to calculate x position of str1.
 315         tw, th = fancytext.GetExtent(str1, dc)
 316         # Centered text.
 317         fancytext.RenderToDC(str1, dc, (bw-tw)/2, 50)
 318 
 319         #------------
 320 
 321         # Need width to calculate x position of str2.
 322         tw, th = fancytext.GetExtent(str2, dc)
 323         # Centered text.
 324         fancytext.RenderToDC(str2, dc, (bw-tw)/2, 70)
 325 
 326         #------------
 327 
 328         # Need width to calculate x position of str3.
 329         tw, th = fancytext.GetExtent(str3, dc)
 330         # Centered text.
 331         fancytext.RenderToDC(str3, dc, (bw-tw)/2, 90)
 332 
 333         #------------
 334 
 335         # Need width to calculate x position of str4.
 336         tw, th = fancytext.GetExtent(str4, dc)
 337         # Centered text.
 338         fancytext.RenderToDC(str4, dc, (bw-tw)/2, 110)
 339 
 340         #------------
 341 
 342         # Need width to calculate x position of str5.
 343         tw, th = fancytext.GetExtent(str5, dc)
 344         # Centered text.
 345         fancytext.RenderToDC(str5, dc, (bw-tw)/2, 150)
 346 
 347         #------------
 348 
 349         # Need width to calculate x position of str6.
 350         tw, th = fancytext.GetExtent(str6, dc)
 351         # Centered text.
 352         fancytext.RenderToDC(str6, dc, (bw-tw)/2, 185)
 353 
 354 
 355     def OnKeyUp(self, event):
 356         """
 357         ...
 358         """
 359 
 360         if event.GetKeyCode() == wx.WXK_ESCAPE:
 361             self.OnCloseWindow(event)
 362 
 363         event.Skip()
 364 
 365 
 366     def OnCloseWindow(self, event):
 367         """
 368         ...
 369         """
 370 
 371         #self.Destroy()
 372         self.OnTimerOut(self)
 373 
 374 #-------------------------------------------------------------------------------
 375 
 376 class MyFirstFrame(wx.Frame):
 377     """
 378     ...
 379     """
 380     style = (wx.CLIP_CHILDREN | wx.CLOSE_BOX |
 381              wx.MINIMIZE_BOX | wx.SYSTEM_MENU |
 382              wx.NO_BORDER | wx.FRAME_SHAPED | # wx.FRAME_NO_TASKBAR
 383              wx.NO_FULL_REPAINT_ON_RESIZE | wx.STAY_ON_TOP)
 384     def __init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString,
 385                  pos=wx.DefaultPosition, size=wx.DefaultSize,
 386                  style=style,
 387                  name='frame'):
 388         wx.Frame.__init__(self, parent, id, title, pos, size, style, name)
 389 
 390         #------------
 391 
 392         # Attributes.
 393         self.delta = wx.Point(0,0)
 394 
 395         #------------
 396 
 397         # Return application name.
 398         self.app_name = wx.GetApp().GetAppName()
 399         # Return bitmaps folder.
 400         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
 401         # Return icons folder.
 402         self.icons_dir = wx.GetApp().GetIconsDir()
 403 
 404         #------------
 405 
 406         # Create a timer.
 407         self.timer = wx.Timer(self)
 408         self.timer.Start(1000)
 409         self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
 410 
 411         #------------
 412 
 413         # Simplified init method.
 414         self.SetProperties()
 415         self.CreateCtrls()
 416         self.BindEvents()
 417 
 418         #------------
 419 
 420         self.CenterOnScreen(wx.BOTH)
 421 
 422     #---------------------------------------------------------------------------
 423 
 424     def SetProperties(self):
 425         """
 426         ...
 427         """
 428 
 429         self.SetTitle(self.app_name)
 430         self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 431 
 432         frameIcon = wx.Icon(os.path.join(self.icons_dir,
 433                                          "icon_wx.ico"),
 434                             type=wx.BITMAP_TYPE_ICO)
 435         self.SetIcon(frameIcon)
 436 
 437 
 438     def CreateCtrls(self):
 439         """
 440         ...
 441         """
 442 
 443         # Load a background bitmap.
 444         self.bitmap = wx.Bitmap(os.path.join(self.bitmaps_dir,
 445                                              "phone.png"),
 446                                 type=wx.BITMAP_TYPE_PNG)
 447         # or
 448         # image = wx.Image('phone.png', wx.BITMAP_TYPE_PNG)
 449         # blurimage = image.Blur(1)
 450         # self.bitmap = blurimage.ConvertToBitmap()
 451 
 452         self.SetClientSize((self.bitmap.GetWidth(), self.bitmap.GetHeight()))
 453 
 454         #------------
 455 
 456         if wx.Platform == "__WXGTK__":
 457             # wxGTK requires that the window be created before you can
 458             # set its shape, so delay the call to SetWindowShape until
 459             # this event.
 460             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 461         else:
 462             # On wxMSW and wxMac the window has
 463             # already been created, so go for it.
 464             self.SetWindowShape()
 465 
 466         #------------
 467 
 468         tt = wx.ToolTip('LeftClick to Drag - RightClick to Close')
 469         self.SetToolTip(tt)
 470 
 471         #------------
 472 
 473         # It appears that we cannot make child widgets on the Frame
 474         # when using mswalpha, there fore we will make a "child" shaped
 475         # frame that will handle widgets transparency also.
 476         # self.button = wx.Button(self, -1, 'Button', pos=(100, 100))
 477 
 478         #------------
 479 
 480         self.Centre()
 481         self.widgetsframe = MySecondFrame(self,
 482                                           pos=self.GetPosition(),
 483                                           size=self.GetSize())
 484         self.widgetsframe.Show()
 485 
 486         #------------
 487 
 488         # Create an accelerator table.
 489         self.accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('X'),
 490                                                wx.ID_EXIT),
 491                                               (wx.ACCEL_CTRL, ord('A'),
 492                                                wx.ID_ABOUT)
 493                                              ])
 494         self.SetAcceleratorTable(self.accel_tbl)
 495 
 496 
 497     def BindEvents(self):
 498         """
 499         Bind some events to an events handle.
 500         """
 501 
 502         self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
 503         self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)
 504 
 505         self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x: None)
 506         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 507         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 508         self.Bind(wx.EVT_MOTION, self.OnMouseMove)
 509         self.Bind(wx.EVT_RIGHT_UP, self.OnExit)
 510         self.Bind(wx.EVT_PAINT, self.OnPaint)
 511 
 512 
 513     def SetWindowShape(self, *event):
 514         """
 515         ...
 516         """
 517 
 518         # Use the bitmap's mask to determine the region.
 519         self.region = wx.Region(self.bitmap)
 520         self.hasShape = self.SetShape(self.region)
 521 
 522 
 523     def OnLeftDown(self, event):
 524         """
 525         ...
 526         """
 527 
 528         if self.HasCapture():
 529             self.ReleaseMouse()
 530 
 531         self.CaptureMouse()
 532         x, y = self.ClientToScreen(event.GetPosition())
 533         originx, originy = self.GetPosition()
 534         dx = x - originx
 535         dy = y - originy
 536         self.delta = (dx, dy)
 537 
 538 
 539     def OnLeftUp(self, event):
 540         """
 541         ...
 542         """
 543 
 544         if self.HasCapture():
 545             self.ReleaseMouse()
 546 
 547 
 548     def OnMouseMove(self, event):
 549         """
 550         ...
 551         """
 552 
 553         if event.Dragging() and event.LeftIsDown():
 554             x, y = self.ClientToScreen(event.GetPosition())
 555             fp = (x - self.delta[0], y - self.delta[1])
 556             self.SetPosition(fp)
 557             self.widgetsframe.SetPosition(fp)
 558 
 559 
 560     def Draw(self):
 561         """
 562         ...
 563         """
 564 
 565         # Return client size.
 566         width, height = self.GetClientSize()
 567 
 568         # Return main image size.
 569         bw, bh = self.bitmap.GetWidth(), self.bitmap.GetHeight()
 570 
 571         #------------
 572 
 573         dc = wx.MemoryDC()
 574 
 575         #------------
 576 
 577         fontSize = self.GetFont().GetPointSize()
 578 
 579         # wx.Font(pointSize, family, style, weight, underline, faceName)
 580         if wx.Platform == "__WXGTK__":
 581             self.normalBoldFont = wx.Font(fontSize-1,
 582                                           wx.DEFAULT, wx.NORMAL,
 583                                           wx.NORMAL, False, "")
 584             self.normalFont = wx.Font(fontSize-2,
 585                                       wx.DEFAULT, wx.NORMAL,
 586                                       wx.NORMAL, False, "")
 587 
 588         else:
 589             self.normalBoldFont = wx.Font(fontSize+23,
 590                                           wx.DEFAULT, wx.NORMAL,
 591                                           wx.NORMAL, False, "")
 592             self.normalFont = wx.Font(fontSize+1,
 593                                       wx.DEFAULT, wx.NORMAL,
 594                                       wx.NORMAL, False, "")
 595 
 596         dc.SetFont(self.normalFont)
 597         dc.SetFont(self.normalBoldFont)
 598 
 599         #------------
 600 
 601         bmp = wx.Bitmap.FromRGBA(width, height, red=0, green=0, blue=0, alpha=0)
 602         dc.SelectObject(bmp)
 603 
 604         #------------
 605 
 606         gc = wx.GraphicsContext.Create(dc)
 607         gcdc = wx.GCDC(gc)
 608 
 609         # Draw a bitmap with an alpha channel
 610         # on top of the last group.
 611         # image, x, y, transparence
 612         gcdc.DrawBitmap(self.bitmap, -1, -1, useMask=False)
 613 
 614         # Draw text.
 615         gcdc.SetTextForeground(wx.Colour(150, 150, 150, 255))  # grey
 616         gcdc.SetTextBackground(wx.TransparentColour)
 617         gcdc.SetFont(self.normalFont)
 618         date = time.strftime("%A %d %B %Y")
 619         tw, th = gcdc.GetTextExtent(date)
 620         gcdc.DrawText(date, (int((bw-tw)/2), int(153)))
 621 
 622         gcdc.SetTextForeground(wx.Colour(255, 255, 255, 255))  # white
 623         gcdc.SetTextBackground(wx.TransparentColour)
 624         gcdc.SetFont(self.normalBoldFont)
 625         hour = time.strftime("%H:%M:%S")  # "%I:%M:%S %p"
 626         tw, th = gcdc.GetTextExtent(hour)
 627         gcdc.DrawText(hour, (int((bw-tw)/2-5), int(110)))
 628 
 629         #------------
 630 
 631         gcdc.Destroy()
 632         del gcdc
 633 
 634         dc.Destroy()
 635         del dc
 636 
 637         #------------
 638 
 639         draw_alpha(self, bmp)
 640 
 641 
 642     def OnTimer(self, event):
 643         """
 644         ...
 645         """
 646 
 647         dc = wx.BufferedDC(wx.ClientDC(self))
 648         dc.Clear()
 649 
 650         self.Draw()
 651 
 652 
 653     def OnPaint(self, event):
 654         """
 655         ...
 656         """
 657 
 658         dc = wx.BufferedPaintDC(self)
 659         dc.Clear()
 660 
 661         self.Draw()
 662 
 663 
 664     def OnAbout(self, event):
 665         """
 666         ...
 667         """
 668 
 669         self.dialog = MyAboutDlg(self)
 670 
 671 
 672     def OnExit(self, event):
 673         """
 674         ...
 675         """
 676 
 677         self.widgetsframe.Close()
 678         self.Close()
 679 
 680 #-------------------------------------------------------------------------------
 681 
 682 class MySecondFrame(wx.Frame):
 683     """
 684     ...
 685     """
 686     def __init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString,
 687                  pos=wx.DefaultPosition, size=wx.DefaultSize,
 688                  style=wx.FRAME_SHAPED |
 689                        wx.NO_BORDER |
 690                        wx.FRAME_NO_TASKBAR |
 691                        wx.FRAME_FLOAT_ON_PARENT,
 692                  name="frame"):
 693         wx.Frame.__init__(self, parent, id, title, pos, size, style, name)
 694 
 695         #------------
 696 
 697         # Attributes.
 698         self.SetTransparent(160)
 699 
 700         #------------
 701 
 702         # Return bitmaps folder.
 703         self.bitmaps_dir = wx.GetApp().GetBitmapsDir()
 704         # Return icons folder.
 705         self.icons_dir = wx.GetApp().GetIconsDir()
 706 
 707         #------------
 708 
 709         # Simplified init method.
 710         self.SetProperties()
 711         self.CreateCtrls()
 712         self.BindEvents()
 713 
 714     #---------------------------------------------------------------------------
 715 
 716     def SetProperties(self):
 717         """
 718         ...
 719         """
 720 
 721         self.SetBackgroundColour(wx.BLACK)
 722 
 723 
 724     def CreateCtrls(self):
 725         """
 726         ...
 727         """
 728 
 729         self.slider = wx.Slider(self, -1,
 730                                 value=160,
 731                                 minValue=64,
 732                                 maxValue=255,
 733                                 pos=(92, 20),
 734                                 style=wx.SL_HORIZONTAL)
 735         self.slider.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 736 
 737         #------------
 738 
 739         # Button About.
 740         self.btn1 = SBBTwo.ShapedBitmapButton(self, -1,
 741             bitmap=wx.Bitmap(os.path.join(self.bitmaps_dir,
 742                                           "btn_about_normal2.png"),
 743                              type=wx.BITMAP_TYPE_PNG),
 744 
 745             pressedBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 746                                               "btn_about_pressed2.png"),
 747                                  type=wx.BITMAP_TYPE_PNG),
 748 
 749             hoverBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 750                                             "btn_about_normal2.png"),
 751                                type=wx.BITMAP_TYPE_PNG),
 752 
 753             disabledBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 754                                                "btn_about_disabled2.png"),
 755                                   type=wx.BITMAP_TYPE_PNG),
 756 
 757             label="",
 758             labelForeColour=wx.WHITE,
 759             labelFont=wx.Font(9,
 760                               wx.FONTFAMILY_DEFAULT,
 761                               wx.FONTSTYLE_NORMAL,
 762                               wx.FONTWEIGHT_BOLD),
 763             style=wx.BORDER_NONE)
 764 
 765         self.btn1.SetPosition((int((220)), int(60)))
 766         self.btn1.SetSize((21, 21))
 767         self.btn1.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 768 
 769         # Button Exit.
 770         self.btn2 = SBBTwo.ShapedBitmapButton(self, -1,
 771             bitmap=wx.Bitmap(os.path.join(self.bitmaps_dir,
 772                                           "btn_exit_normal.png"),
 773                              type=wx.BITMAP_TYPE_PNG),
 774 
 775             pressedBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 776                                               "btn_exit_pressed.png"),
 777                                  type=wx.BITMAP_TYPE_PNG),
 778 
 779             hoverBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 780                                             "btn_exit_normal.png"),
 781                                type=wx.BITMAP_TYPE_PNG),
 782 
 783             disabledBmp=wx.Bitmap(os.path.join(self.bitmaps_dir,
 784                                                "btn_exit_disabled.png"),
 785                                   type=wx.BITMAP_TYPE_PNG),
 786 
 787             label="",
 788             labelForeColour=wx.WHITE,
 789             labelFont=wx.Font(9,
 790                               wx.FONTFAMILY_DEFAULT,
 791                               wx.FONTSTYLE_NORMAL,
 792                               wx.FONTWEIGHT_BOLD),
 793             style=wx.BORDER_NONE)
 794 
 795         self.btn2.SetPosition((int((118)), int(422)))
 796         self.btn2.SetSize((50, 50))
 797         self.btn2.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
 798 
 799         #------------
 800 
 801         if wx.Platform == "__WXGTK__":
 802             # wxGTK requires that the window be created before you can
 803             # set its shape, so delay the call to SetWindowShape until
 804             # this event.
 805             self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
 806         else:
 807             # On wxMSW and wxMac the window has
 808             # already been created, so go for it.
 809             self.SetWindowShape()
 810 
 811 
 812     def BindEvents(self):
 813         """
 814         Bind some events to an events handler.
 815         """
 816 
 817         self.slider.Bind(wx.EVT_SLIDER, self.OnSlider)
 818         self.btn1.Bind(wx.EVT_BUTTON, self.OnBtnAbout)
 819         self.btn2.Bind(wx.EVT_BUTTON, self.OnBtnClose)
 820 
 821         self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
 822         self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
 823 
 824 
 825     def SetWindowShape(self, *event):
 826         """
 827         ...
 828         """
 829 
 830         # Use the widget's rect's to determine the region.
 831         wxRegion = wx.Region
 832         self.region = wxRegion()
 833         widgets = [child for child in self.GetChildren()]
 834         regions = [wxRegion(widget.GetRect()) for widget in widgets]
 835         Union = self.region.Union
 836         [Union(reg) for reg in regions]
 837         self.hasShape = self.SetShape(self.region)
 838 
 839 
 840     def OnLeftDown(self, event):
 841         """
 842         ...
 843         """
 844 
 845         if self.HasCapture():
 846             self.ReleaseMouse()
 847 
 848         self.CaptureMouse()
 849         x, y = self.ClientToScreen(event.GetPosition())
 850         originx, originy = self.GetPosition()
 851         dx = x - originx
 852         dy = y - originy
 853         self.delta = (dx, dy)
 854 
 855 
 856     def OnLeftUp(self, event):
 857         """
 858         ...
 859         """
 860 
 861         if self.HasCapture():
 862             self.ReleaseMouse()
 863 
 864 
 865     def OnBtnAbout(self, event):
 866         """
 867         ...
 868         """
 869 
 870         self.GetParent().OnAbout(self)
 871 
 872 
 873     def OnBtnClose(self, event):
 874         """
 875         ...
 876         """
 877 
 878         self.GetParent().OnExit(self)
 879 
 880         print("Close button was clicked.")
 881 
 882 
 883     def OnSlider(self, event):
 884         """
 885         ...
 886         """
 887 
 888         self.SetTransparent(event.GetEventObject().GetValue())
 889 
 890 #-------------------------------------------------------------------------------
 891 
 892 class MyApp(wx.App):
 893     """
 894     Thanks to Andrea Gavana.
 895     """
 896     def OnInit(self):
 897 
 898         #------------
 899 
 900         self.locale = wx.Locale(wx.LANGUAGE_FRENCH)
 901 
 902         #------------
 903 
 904         self.SetAppName("Custom Gui 2")
 905 
 906         #------------
 907 
 908         self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
 909 
 910         #------------
 911 
 912         frame = MyFirstFrame(None)
 913         self.SetTopWindow(frame)
 914         frame.Show(True)
 915 
 916         return True
 917 
 918     #---------------------------------------------------------------------------
 919 
 920     def GetInstallDir(self):
 921         """
 922         Returns the installation directory for my application.
 923         """
 924 
 925         return self.installDir
 926 
 927 
 928     def GetIconsDir(self):
 929         """
 930         Returns the icons directory for my application.
 931         """
 932 
 933         icons_dir = os.path.join(self.installDir, "icons")
 934         return icons_dir
 935 
 936 
 937     def GetBitmapsDir(self):
 938         """
 939         Returns the bitmaps directory for my application.
 940         """
 941 
 942         bitmaps_dir = os.path.join(self.installDir, "bitmaps")
 943         return bitmaps_dir
 944 
 945 #-------------------------------------------------------------------------------
 946 
 947 def main():
 948     app = MyApp(False)
 949     app.MainLoop()
 950 
 951 #-------------------------------------------------------------------------------
 952 
 953 if __name__ == "__main__" :
 954     wxVER = 'wxPython %s' % wx.version()
 955     pyVER = 'python %d.%d.%d.%s' % sys.version_info[0:4]
 956     versionInfos = '%s %s' % (wxVER, pyVER)
 957     print(versionInfos)
 958     main()


Third example

[ATTACH]

   1 # sample_three.py


Download source

source.zip


Additional Information

Link :

https://hasenj.wordpress.com/2009/04/14/making-a-fancy-window-in-wxpython/

https://stackoverflow.com/questions/17479254/panel-doesnt-fully-refresh-when-using-a-custom-background-in-wxpython

https://stackoverflow.com/questions/12087140/custom-window-frame-and-window-appearance-with-wxpython

https://github.com/Metallicow/MCOW

https://github.com/Eseeme/wxpython-custom-button

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Kevin Schlosser {OK} and Metallicow {OK} , Robin Dunn, Pascal Faut., the wxPython community...

Thanks also to all known contributors or anonymous that I forgot.

And finally, congratulations to the many forums and blogs for all the available examples and the help which is the strength of wxPython. ;)


About this page

Date (d/m/y) Person (bot) Comments :

21/09/20 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah....

How to create a customized frame - Part 6 (Phoenix) (last edited 2020-12-13 18:20:20 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.