- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Creating custom widgets
Toolkits usually provide only the most common widgets like buttons, text widgets, scrollbars, sliders etc. No toolkit can provide all possible widgets. wxPython has many widgets; more specialised widgets are created by client programmers.
Custom widgets are created in two ways: either we modify or enhance an existing widget, or we create a custom widget from scratch.
A hyperlink widget
The first example will create a hyperlink. The hyperlink widget will be based on an existing wx.lib.stattext.GenStaticText
widget.
#!/usr/bin/python import wx from wx.lib.stattext import GenStaticText import webbrowser class Link(GenStaticText): def __init__(self, *args, **kw): super(Link, self).__init__(*args, **kw) self.font1 = wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, True, 'Verdana') self.font2 = wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False, 'Verdana') self.SetFont(self.font2) self.SetForegroundColour('#0000ff') self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvent) self.Bind(wx.EVT_MOTION, self.OnMouseEvent) def SetUrl(self, url): self.url = url def OnMouseEvent(self, e): if e.Moving(): self.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) self.SetFont(self.font1) elif e.LeftUp(): webbrowser.open_new(self.url) else: self.SetCursor(wx.NullCursor) self.SetFont(self.font2) e.Skip() class Example(wx.Frame): def __init__(self, *args, **kw): super(Example, self).__init__(*args, **kw) self.InitUI() def InitUI(self): panel = wx.Panel(self) lnk = Link(panel, label='ZetCode', pos=(10, 60)) lnk.SetUrl('http://www.zetcode.com') motto = GenStaticText(panel, label='Knowledge only matters', pos=(10, 30)) motto.SetFont(wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD, False, 'Verdana')) self.SetSize((220, 150)) self.SetTitle('A Hyperlink') self.Centre() self.Show(True) def main(): ex = wx.App() Example(None) ex.MainLoop() if __name__ == '__main__': main()
This hyperlink widget is based on an existing widget. In this example we do not draw anything, we just use an existing widget, which we modify a bit.
from wx.lib.stattext import GenStaticText import webbrowser
Here we import the base widget from which we derive our hyperlink widget and the webbrowser module. The webbrowser module is a standard Python module. We will use it to open links in a default browser.
self.SetFont(self.font2) self.SetForegroundColour('#0000ff')
The idea behind creating a hyperlink widget is simple. We inherit from a base wx.lib.stattext.GenStaticText
widget class. So we have a text widget. Then we modify it a bit. We change the font and the colour of the text.
if e.Moving(): self.SetCursor(wx.StockCursor(wx.CURSOR_HAND)) self.SetFont(self.font1)
If we hover a mouse pointer over the link, we change the font to underlined and also change the mouse pointer to a hand cursor.
elif e.LeftUp(): webbrowser.open_new(self.url)
If we left click on the link, we open the link in a default browser.

Burning widget
This is an example of a widget that we create from a ground up. We put a wx.Panel
on the bottom of the window and draw the entire widget manually. If you have ever burned a CD or a DVD, you already saw this kind of widget.
To avoid flicker on Windows, use need to use double buffering.
#!/usr/bin/python # burning.py import wx class Widget(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, size=(-1, 30), style=wx.SUNKEN_BORDER) self.parent = parent self.font = wx.Font(9, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, 'Courier 10 Pitch') self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_SIZE, self.OnSize) def OnPaint(self, event): num = range(75, 700, 75) dc = wx.PaintDC(self) dc.SetFont(self.font) w, h = self.GetSize() self.cw = self.parent.GetParent().cw step = int(round(w / 10.0)) j = 0 till = (w / 750.0) * self.cw full = (w / 750.0) * 700 if self.cw >= 700: dc.SetPen(wx.Pen('#FFFFB8')) dc.SetBrush(wx.Brush('#FFFFB8')) dc.DrawRectangle(0, 0, full, 30) dc.SetPen(wx.Pen('#ffafaf')) dc.SetBrush(wx.Brush('#ffafaf')) dc.DrawRectangle(full, 0, till-full, 30) else: dc.SetPen(wx.Pen('#FFFFB8')) dc.SetBrush(wx.Brush('#FFFFB8')) dc.DrawRectangle(0, 0, till, 30) dc.SetPen(wx.Pen('#5C5142')) for i in range(step, 10*step, step): dc.DrawLine(i, 0, i, 6) width, height = dc.GetTextExtent(str(num[j])) dc.DrawText(str(num[j]), i-width/2, 8) j = j + 1 def OnSize(self, event): self.Refresh() class Burning(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(330, 200)) self.cw = 75 panel = wx.Panel(self, -1) CenterPanel = wx.Panel(panel, -1) self.sld = wx.Slider(CenterPanel, -1, 75, 0, 750, (-1, -1), (150, -1), wx.SL_LABELS) vbox = wx.BoxSizer(wx.VERTICAL) hbox = wx.BoxSizer(wx.HORIZONTAL) hbox2 = wx.BoxSizer(wx.HORIZONTAL) hbox3 = wx.BoxSizer(wx.HORIZONTAL) self.wid = Widget(panel, -1) hbox.Add(self.wid, 1, wx.EXPAND) hbox2.Add(CenterPanel, 1, wx.EXPAND) hbox3.Add(self.sld, 0, wx.TOP, 35) CenterPanel.SetSizer(hbox3) vbox.Add(hbox2, 1, wx.EXPAND) vbox.Add(hbox, 0, wx.EXPAND) self.Bind(wx.EVT_SCROLL, self.OnScroll) panel.SetSizer(vbox) self.sld.SetFocus() self.Centre() self.Show(True) def OnScroll(self, event): self.cw = self.sld.GetValue() self.wid.Refresh() app = wx.App() Burning(None, -1, 'Burning widget') app.MainLoop()
All the important code resides in the OnPaint()
method of the Widget class. This widget shows graphically the total capacity of a medium and the free space available to us. The widget is controlled by a slider widget. The minimum value of our custom widget is 0, the maximum is 750. If we reach value 700, we began drawing in red colour. This normally indicates overburning.
w, h = self.GetSize() self.cw = self.parent.GetParent().cw ... till = (w / 750.0) * self.cw full = (w / 750.0) * 700
We draw the widget dynamically. The greater the window, the greater the burning widget. And vice versa. That is why we must calculate the size of the wx.Panel
onto which we draw the custom widget. The till parameter determines the total size to be drawn. This value comes from the slider widget. It is a proportion of the whole area. The full parameter determines the point, where we begin to draw in red colour. Notice the use of floating point arithmetics. This is to achieve greater precision.
The actual drawing consists of three steps. We draw the yellow or red and yellow rectangle. Then we draw the vertical lines, which divide the widget into several parts. Finally, we draw the numbers, which indicate the capacity of the medium.
def OnSize(self, event): self.Refresh()
Every time the window is resized, we refresh the widget. This causes the widget to repaint itself.
def OnScroll(self, event): self.cw = self.sld.GetValue() self.wid.Refresh()
If we scroll the thumb of the slider, we get the actual value and save it into the self.cw
parameter. This value is used, when the burning widget is drawn. Then we cause the widget to be redrawn.


The CPU widget
There are system applications that measure system resources. The temperature, memory and CPU consuption etc. By displaying a simple text like CPU 54% you probably won't impress your users. Specialized widgets are created to make the application more appealing.
The following widget is often used in system applications.
A remark for windows users: to avoid flicker, we use double buffering. We change the size of the application and the width of the slider.
#!/usr/bin/python # cpu.py import wx class CPU(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id, size=(80, 110)) self.parent = parent self.SetBackgroundColour('#000000') self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, event): dc = wx.PaintDC(self) dc.SetDeviceOrigin(0, 100) dc.SetAxisOrientation(True, True) pos = self.parent.GetParent().GetParent().sel rect = pos / 5 for i in range(1, 21): if i > rect: dc.SetBrush(wx.Brush('#075100')) dc.DrawRectangle(10, i*4, 30, 5) dc.DrawRectangle(41, i*4, 30, 5) else: dc.SetBrush(wx.Brush('#36ff27')) dc.DrawRectangle(10, i*4, 30, 5) dc.DrawRectangle(41, i*4, 30, 5) class CPUWidget(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(190, 140)) self.sel = 0 panel = wx.Panel(self, -1) centerPanel = wx.Panel(panel, -1) self.cpu = CPU(centerPanel, -1) hbox = wx.BoxSizer(wx.HORIZONTAL) self.slider = wx.Slider(panel, -1, self.sel, 0, 100, (-1, -1), (25, 90), wx.VERTICAL | wx.SL_LABELS | wx.SL_INVERSE) self.slider.SetFocus() hbox.Add(centerPanel, 0, wx.LEFT | wx.TOP, 20) hbox.Add(self.slider, 0, wx.LEFT | wx.TOP, 23) self.Bind(wx.EVT_SCROLL, self.OnScroll) panel.SetSizer(hbox) self.Centre() self.Show(True) def OnScroll(self, event): self.sel = event.GetInt() self.cpu.Refresh() app = wx.App() CPUWidget(None, -1, 'cpu') app.MainLoop()
Creating this widget is quite simple. We create a black panel. Then we draw small rectangles onto this panel. The colour of the rectangles depend on the value of the slider. The colour can be dark green or bright green.
dc.SetDeviceOrigin(0, 100) dc.SetAxisOrientation(True, True)
Here we change the default coordinate system to cartesian. This is to make the drawing intuitive.
pos = self.parent.GetParent().GetParent().sel rect = pos / 5
Here we get the value of the sizer. We have 20 rectangles in each column. The slider has 100 numbers. The rect parameter makes a convertion from slider values into rectangles that will be drawn in bright green colour.
for i in range(1, 21): if i > rect: dc.SetBrush(wx.Brush('#075100')) dc.DrawRectangle(10, i*4, 30, 5) dc.DrawRectangle(41, i*4, 30, 5) else: dc.SetBrush(wx.Brush('#36ff27')) dc.DrawRectangle(10, i*4, 30, 5) dc.DrawRectangle(41, i*4, 30, 5)
Here we draw 40 rectangles, 20 in each column. If the number of the rectangle being drawn is greater than the converted rect value, we draw it in a dark green colour. Otherwise in bright green.

In this chapter, we have created custom widgets in wxPython.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论