Wxpython cookbook download pdf
The Config File We need to create some sort of configuration file that we can use to generate our dialog. The Labels section has the labels we will use to create wx. StaticText controls with. The Values section has some sample values we can use for the corresponding text control widgets and one combo box.
The first item in the list will be the default option in the combo box and the other two items are the real contents of the widget. Dialog : 6 """ 7 Creates and displays a preferences dialog that allows the user to 8 change some settings. Font 12, wx. SWISS, wx. SetFont font 41 lblSizer. Add lbl, 0, wx. Add cbo, 0, wx. Add txt, 0, wx. Button self, wx. AddButton cancelBtn 64 btnSizer. Realize 65 66 colSizer. Add lblSizer 67 colSizer. Add valueSizer, 1, wx. Add colSizer, 0, wx.
SetSizer mainSizer 71 72 def onSave self, event : 73 """ 74 Saves values to disk 75 """ 76 for name in self. FindWindowByName name 78 if isinstance widget, wx. GetItems 81 choices. GetValue 85 self. EndModal 0 88 89 90 class MyApp wx. ShowModal 97 dlg. MainLoop To start, we subclass a wx. Dialog and use its createWidgets method. This method will read our config file and use the data therein to create the display. Once the config is read, we loop over the keys in the Labels section and create static text controls as needed.
Next, we loop over the values in the other section and use a conditional to check the type of widget. In this case, we only care about wx. TextCtrl and wx. This is where ConfigObj helps since it actually can typecast some of the entries in our configuration file.
Note that for the text controls and combo box, I set the name field. Anyway, in both loops, we use vertical BoxSizers to hold our widgets. I personally really like BoxSizers. I also used a StdDialogButtonSizer for the buttons. If you use the correct standard ids for the buttons, this sizer will place them in the right order in a cross-platform way. The next method that we care about is onSave. Here is where we save whatever the user has entered. Earlier in the program, I grabbed the widget names from the configuration and we loop over those now.
We call wx. FindWindowByName to find the widget by name. Then we use isinstance again to check what kind of widget we have. When the loop finishes, we write the data to disk. The last step is to call EndModal 0 to close the dialog and, in turn, the application. Wrapping Up Now you know the basics of generating a dialog from a configuration file.
I think using some kind of dictionary with widget type names probably in strings might be an easy way to make this script work with other widgets.
You will also note that I have no validation in this example at all! This is something for you to do to extend this piece of code. Use your imagination and let me know what you come up with. Recipe Saving Data to a Config File There are lots of ways for you to persist your data in your application. You could use a simple database, like SQLite or you could use a configuration file. For this example, we will opt for the configuration file.
Python has a handy library built into it called configparser that you can use for creating and manipulating config files. Getting Started ConfigObj is a bit easier to use than configparser and provides validation too. It can also return Python types from the config file, which configparser just returns strings.
Creating a Controller It is common when designing a user interface to follow the model-view-controller paradigm. The controller usually houses the code that actully does something, like reading and writing data from a config file.
The model is usually a description of a database or even the widgets themselves, which wxPython supports via XRC. The view is the code that draws the interface for the user, so in this case, it will be the majority of the wxPython code.
ConfigObj 15 config. ConfigObj inifile This piece of code is pretty straightforward. The config file gets six fields, but no sections. Regardless, the function returns a ConfigObj object to the caller. Dialog class to create a preferences dialog. Font 16, wx. SetFont font This first chunk just create a simple button to close the application. We abstracted it out to make sharing this code simpler. You could even put this code into its own module that could be imported by multiple applications, for example.
Dialog : 2 """ 3 Creates and displays a preferences dialog that allows the user to 4 change some settings. TextCtrl self 18 self. TextCtrl self 22 self. SetFont font 41 self.
TextCtrl self, wx. AddGrowableCol 1 66 67 prefSizer. Add serverLbl, 0, wx. Add usernameLbl, 0, wx. Add passwordLbl, 0, wx. Add updateLbl, 0, wx. Add minutesLbl, 0, wx. Add updateSizer 77 prefSizer. Add agencyLbl, 0, wx. Add 20,20 80 prefSizer. Add prefSizer, 0, wx. ALL, 5 83 btnSizer. Add saveBtn, 0, wx. ALL, 5 84 btnSizer. SetSizer mainSizer 87 88 load preferences 89 self. It also sets up event handlers and sets the same font characteristics across all the widgets.
SetValue updateServer 14 self. SetValue username 15 self. SetValue password 16 self. SetValue interval 17 self. SetValue agencyFilter 18 self. SetValue filters 19 20 21 def onCancel self, event : 22 """ 23 Closes the dialog 24 """ 25 self. MessageDialog 51 self, "Preferences Saved! ShowModal 54 dlg. ShowModal 60 dlg. Destroy The code above allows us to load a configuration from a file using ConfigObj. You can see how that works by reading the code in the loadPreferences method. The other major piece is how the code saves the preferences when the user changes them.
For that, we need to look at the savePreferences method. The main reason for that is that in my original program, I use a space as the delimiter and the program needed to convert commas and such to spaces.
This code is still a work in progress though as it does not cover all the cases that a user could enter. Feel free to expand it to cover more edge cases. You will also note that to close our Dialog correctly, we called EndModal in our onCancel method. All that is required to do so is to add or delete it in the configuration file.
ConfigObj will pick up the changes and we just need to remember to add or remove the appropriate widgets in our GUI.
Give it a try and find out just how easy it is! Wrapping Up At this point, you should be able to create your own preferences dialog and use ConfigObj to populate it. I think you will too. Recipe Binding Multiple Widgets to the Same Handler From time to time, you will find that you need to have multiple buttons call the same event handler.
Usually this happens when you have more than one button that do very similar things. Getting Started To begin, we will write some code that contains multiple buttons. We will go through an example that shows two different ways to get the button object so you can manipulate your program as needed. SetSizer sizer 21 22 def buildButtons self, btn, sizer : 23 """""" 24 btn. Show 45 app. MainLoop To start, we create three button objects. Then to make things slightly less messy, we put them into a list and iterate over the list to add the buttons to a sizer and bind them to an event handler.
This is a good way to cut down on spaghetti code i. Some people go ahead and create some elaborate helper methods like buildButtons that can handle other widgets and are more flexible. The part we really care about though is the event handler itself. That will return the widget and then you can do whatever you like. The functionality is up to you.
The second way to get the widget is a two-step process where we need to extract the ID from the event using its GetID method. All you really need to know is that if you write two functions that do the same thing or you copy and paste a function and only make minimal changes, then you should refactor your code to prevent issues down the road.
Recipe How to Fire Multiple Event Handlers There are a few occasions where you will want to fire a series of event handlers. Fortunately, wxPython makes it very easy to accomplish.
HandlerOne 12 btn. HandlerTwo 13 14 def HandlerOne self, event : 15 """""" 16 print "handler one fired! Skip 18 19 def HandlerTwo self, event : 20 """""" 21 print "handler two fired! Skip 23 24 25 class MyFrame wx. The next key piece is that you have to use event. Skip will cause wxPython to look for other handlers that may need to handle the event. The book, wxPython in Action by Robin Dunn explains this concept really well. Wrapping Up While this recipe is on the short side, it demonstrates one of the many powerful features of the wxPython GUI toolkit.
That feature is the ability to bind a widget to multiple event handlers. You might find this useful if you need to save off some information to a database while also calling a long-running process, for example. So I did some investigation into the subject and there is nothing builtin to wxPython that does this task. Robin Dunn, creator of wxPython, recommended that I should create a dictionary of the events and their ids to accomplish this feat. After a brief Google search, I found a forum thread where Robin Dunn described how to do it.
PyEventBinder : 8 eventDict[evt. There are special events in some of the sub-libraries in wx, such as in wx. You will have to account for that sort of thing. PyEventBinder : 15 self. PyEventBinder : 21 self. Button panel, wx. GetEventType 35 print self. Show 41 app. MainLoop As you can see, we changed the loop slightly.
We took the loop in the first example and combined it with the first IF statement to create a list comprehension. This returns a list of event name strings. Then we loop over that using the other conditionals to add to the dictionary. We do it twice, once for the regular events and then again for the wx. Then we bind a few events to test our event dictionary. If you run this program, you will see that if you execute any of the bound events, it will print those event names to stdout. Since we set the wx.
This can be helpful when debugging as sometimes you want to bind multiple events to one handler and you need to check and see which event was fired. Happy coding! Catching Key Events Catching key events is very easy to do in wxPython. Show 25 app. MainLoop You will notice that the only widgets of consequence in this piece of code are a panel and a button. The event only fires if the button has focus.
Skip at the end. I wanted to be able to detect these keys so that if I was editing a cell, an arrow key press would make the selection change to a different cell.
That is not the default behavior. In a grid, each cell has its own editor and pressing the arrow keys just moves the cursor around within the cell. Check it out below: 1 import wx 2 3 class MyForm wx. SetSizer sizer 18 19 def onWidgetSetup self, widget, event, handler, sizer : 20 widget.
Bind event, handler 21 sizer. Add widget, 0, wx. Show 43 app. MainLoop If you run the code above, try clicking the button and then pressing the spacebar.
Then change the focus to the text control and hit your delete key. If you do that, you should see something like the following screenshot: Try pressing other keys and you will see the key codes printed out for each key.
Admittedly, this code is mostly for illustration. CmdDown rather than event. Catching Char Events Catching char events is a little bit harder, but not not by much. Show 32 app.
MainLoop I think the main thing that is different is that you want to check for accents or international characters. As Robin Dunn explained it to me, on non-US keyboards then part of cooking the key events into char events is mapping the physical keys to the national keyboard map, to produce characters with accents, umlauts, and such.
You should be able to catch ALT here as well, but I noticed that this does not work on my Windows 7 machine or my Macbook. Wrapping Up At this point you should be capable of writing your own desktop application that can capture key and char events.
You might also want to check out the next recipe which is on a similar topic, namely the AcceleratorTable. This class allows the developer to capture key combinations that the user strikes whilst running your program. Check it out when you get a chance. You probably used it to transfer some files from one folder to another this week!
The wxPython GUI toolkit provides drag and drop functionality baked in. Getting Started wxPython provides several different kinds of drag and drop. PyDropTarget The first two are pretty self-explanatory. The last one, wx. PyDropTarget, is just a loose wrap- per around wx. DropTarget itself. It adds a couple extra convenience methods that the plain wx. FileDropTarget example. SetInsertionPointEnd 18 self. ALL, 5 42 sizer. ALL, 5 43 self. SetSizer sizer 44 45 def SetInsertionPointEnd self : 46 """ 47 Put insertion point at end of text control to prevent overwriting 48 """ 49 self.
SetInsertionPointEnd 50 51 def updateText self, text : 52 """ 53 Write text to the text control 54 """ 55 self. WriteText text 56 57 58 class DnDFrame wx. The first thing to do is to subclass wx. Inside that we have one overridden method, OnDropFiles. We have two more methods in our panel class that the drop target class calls to update the text control: SetInsertionPointEnd and updateText.
Note that since we are passing the panel object as the drop target, we can call these methods whatever we want to. TextDropTarget is used when you want to be able to drag and drop some selected text into a text control. Probably one of the most common examples is dragging a URL on a web page up to the address bar or some text up into the search box in Firefox.
SetSizer sizer 35 36 def WriteText self, text : 37 self. WriteText text 38 39 40 class DnDFrame wx. MainLoop Once again we have to subclass our drop target class. In this case, we call it MyTextDropTarget. The OnDropText method writes text out to the text control. The fun bit about this demo is that you not only get to create a widget that can accept dragged text but you also can drag some text from another widget back to your browser! URLDataObject ; 11 self. SetDataObject self. GetData : 18 return wx.
GetURL 21 self. SetFont font 38 self. SetFont font 48 self. Add firstSizer, 0, wx. Add secondSizer, 0, wx. TextCtrl : 66 sizer. Add widget, 1, wx. ALL, 5 67 else: 68 sizer. URLDataObject 76 data. DropSource self. MainLoop The first class is our drop target class.
Here we create a wx. The second text control is where we need to pay attention. In the mouse movement event handler OnStartDrag , we check to make sure that the user is dragging. Next we create an instance of a DropSource and pass it our second text control since it IS the source. Finally we call DoDragDrop on our drop source the text control which will respond by moving, copying, canceling or failing.
Note: Some web browsers may not work with this code. SetObjects self. We have our FileDropTarget subclass, we connect the panel to it and then the ObjectListView widget to the drop target instance. We also have a generic class for holding our file-related data. You would probably need to walk the folder and add up the sizes of the files therein to get that to work.
Feel free to fix that on your own. Anyway, the meat of the program is in the updateDisplay method. Wrapping Up At this point, you should now know how to do at least 3 different types of drag and drop in wxPython. Hopefully you will use this new information responsibly and create some fresh open source applications in the near future. Recipe How to Drag and Drop a File From Your App to the OS A somewhat common use case that you will come across is the need to be able to drag and drop a file from your own custom application to the file system.
In the previous recipe you saw an example of dragging files into your application. Getting Started You will probably want to use a wx. ListCtrl or an ObjectListView widget as they would be the most common widgets to display file information with.
InsertColumn 0, 'Name' 15 self. InsertColumn 1, 'Ext' 16 self. InsertColumn 2, 'Size', 17 wx. InsertColumn 3, 'Modified' 19 20 self. SetColumnWidth 0, 21 self. SetColumnWidth 1, 70 22 self. SetColumnWidth 2, 23 self. SetStringItem j, 1, ext 33 self. SetStringItem 35 j, 3, time. SetItemImage j, 1 40 elif 'py' in ext: 41 self. SetItemImage j, 3 44 elif 'pdf' in ext: 45 self.
SetItemImage j, 4 46 else: 47 self. BoxSizer 63 sizer. Add p1, 1, wx. SetSizer sizer 65 66 self. Center 67 self. GetItem id. DropSource obj 83 dropSource. MainLoop There are a couple of important points here. Then in your handler you need to create a wx. FileDataObject object and use its AddFile method to append a full path to its internal file list.
I will note that it also worked for me on Xubuntu Wrapping Up At this point you should have an idea of how you might make your own application be able to drag a file from it to your Desktop. In other words, he wanted to be able to edit the code and basically refresh the application without closing it and re-running his code. Creating the Reloading App Creating the reloading application is very straight-forward.
All we need is some application code to reload dynamically. Python will do the rest. Add showAppBtn, 0, wx. Add reloadBtn, 0, wx. SetSizer mainSizer 24 25 def onReload self, event : 26 """ 27 Reload the code! Close 31 try: 32 reload testApp 33 except NameError: 34 reload doesn't exist in Python 3. TestFrame 55 56 57 class ReloaderFrame wx.
In this case, the module is called testApp and the file is testApp. Now we need to create the testApp. Creating the Dynamic Application Now we just need to create a super simple application that we can update and then reload it with our reloader application. MainLoop Now all you have to do is edit this second file and reload it with the first file to see the changes. I recommend adding a button in the TestPanel class, saving it and then hitting the Reload button in the other script to see the changes.
However this is a fun way to use wxPython and learn how Python itself works. Besides, part of development is finding new and fun ways to code something. It also provides a few different handlers to save the data it contains into various formats. One of those happens to be XML. RichTextCtrl self 16 self. ALL, 6 23 sizer. ALL, 6 24 25 self. GetBuffer 32 handler. First we create our lovely application and add an instance of the RichTextCtrl widget to the frame along with a button for saving whatever we happen to write in said widget.
Next we set up the binding for the button and layout the widgets. Lastly, we create our event handler. This is where the magic happens. But instead of writing to a file, we write to a file-like object, which is our StringIO instance. We do this so we can write the data to memory and then read it back out. The reason we do this is because the person on StackOverflow wanted a way to extract the XML that the RichTextCtrl generates and write it to a database.
We could have written it to disk first and then read that file, but this is less messy and faster. Instead you would read and write the data in chunks. Anyway, this code works for what we wanted to do.
I hope you found this useful. It was certainly fun to figure out. In this next section, we will update the example so that it will! You will need to use SaveFile instead. The other problem is actually one introduced by Python 3. So for our next example, I updated the code to support both Python 3 and wxPython Phoenix. SetSizer sizer 26 self. The XML that is printed out is a binary string, so if you plan to parse that, then you may need to cast that result into a string.
This can be a useful tool to have should you need to save the data in your application off to a database or some other data storage. The wxPython toolkit provides a simple way to accomplish this feat by changing the alpha transparency of the any top-level widget. For this example I will use a frame object as the top level object and a timer to change the alpha transparency by a unit of 5 every second.
The range of values is 0 - with 0 being completely transparent and being completely opaque. SetTransparent self. Timer self, wx. Start 60 16 self.
AlphaCycle 17 18 def AlphaCycle self, evt : 19 """ 20 Fade the frame in and out 21 """ 22 self. Show 35 app. MainLoop As you can see, all you need to do to change the transparency of the top-level widget is to call the SetTransparent method of that widget and pass it the amount to set. I have actually used this method in some of my past applications when I needed to fade in an alert, such as when I needed to let a user know that they had received a new email.
There is also the ToasterBox widget in wx. You should check it out! Recipe Making Your Text Flash Back in the early days of the Internet, there were a lot of website that had flashing text and banner ads that were supposed to get your attention.
I was even asked to create one in my brief stint as a web developer. Some people want the blinky text in their desktop applications too. So in this recipe we will learn how to do this. SetFont self. Timer self 19 self. SetLabel self. SetForegroundColour random.
StaticText instance and a wx. Creating Changing Text Some managers might want to give the application some extra bling by making the text change as will as blink. Timer self 18 self. SetLabel "Oops! It is also targeted at Python 2 and Python 3 and is written for developers who already have experience with Python and wxPython.
This book does not contain an introduction to wxPython or Python. Michael has been programming with Python since He is the author of the popular Python blog, The Mouse Vs. He is also a contributor on Real Python. Michael released his first book, Python , June 3rd, He wrote the follow up, Python Intermediate Python and published it in the summer of See full terms.
If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid including free.
The formats that a book includes are shown at the top right corner of this page. Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device. Learn more about Leanpub's ebook formats and where to read them. You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!
Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.
Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. It really is that easy. Haskell for FPGA Hardware Design: Use abstractions like monads and lenses to implement 's retro-computing devices like arcade machines and home computers.
This is an intermediate textbook on Emacs Lisp. Learn how to write your own commands and make Emacs truly your editor, suited to your needs! A Functional Programming book from beginner to advanced without skipping a single step along the way.
In my 40 years of programming, I've felt that programming books always let me down, especially Functional Programming books. Python is a widely used general-purpose, high-level programming language. It provides constructs intended to enable clear programs on both a small and large scale. It is the third most popular language whose grammatical syntax is not predominantly based on C. Python is also very easy to code and is also highly flexible, which is exactly what is required for game development.
The user-friendliness of this language allows beginners to code games without too much effort or training. Python Game Programming by Example enables readers to develop cool and popular games in Python without having in-depth programming knowledge of Python. The book includes seven hands-on projects developed with several well-known Python packages, as well as a comprehensive explanation about the theory and design of each game.
It will teach readers about the techniques of game design and coding of some popular games like Pong and tower defense. Thereafter, it will allow readers to add levels of complexities to make the games more fun and realistic using 3D. At the end of the book, you will have added several GUI libraries like Chimpunk2D, cocos2d, and Tkinter in your tool belt, as well as a handful of recipes and algorithms for developing games with Python.
Style and approach This book is an example-based guide that will teach you to build games using Python. This book follows a step-by-step approach as it is aimed at beginners who would like to get started with basic game development. By the end of this book you will be competent game developers with good knowledge of programming in Python.
This book mainly focuses on using Python's built-in tkinter GUI framework. You'll also learn how to use threading to ensure that your GUI doesn't become unresponsive. Toward the end, you'll learn about the versatile PyQt GUI framework, which comes along with its own visual editor that allows you to design GUIs using drag and drop features.
Portable, powerful, and a breeze to use, Python is the popular open source object-oriented programming language used for both standalone programs and scripting applications.
Updated for Python 2. Like its predecessor, the new edition provides solutions to problems that Python programmers face everyday. It now includes over recipes that range from simple tasks, such as working with dictionaries and list comprehensions, to complex tasks, such as monitoring a network and building a templating system. This revised version also includes new chapters on topics such as time, money, and metaprogramming.
Here's a list of additional topics covered: Manipulating text Searching and sorting Working with files and the filesystem Object-oriented programming Dealing with threads and processes System administration Interacting with databases Creating user interfaces Network and web programming Processing XML Distributed programming Debugging and testing Another advantage of The Python Cookbook, 2nd Edition is its trio of authors--three well-known Python programming experts, who are highly visible on email lists and in newsgroups, and speak often at Python conferences.
With scores of practical examples and pertinent background information, The Python Cookbook, 2nd Edition is the one source you need if you're looking to build efficient, flexible, scalable, and well-integrated systems. As Python is such a great and easy to learn language, this book is also ideal for any developer with experience of other languages and enthusiasm to expand their horizon.
This book will guide you through the very basics of creating a fully functional GUI in Python with only a few lines of code. Each and every recipe adds more widgets to the GUIs we are creating. While the cookbook recipes all stand on their own, there is a common theme running through all of them. As our GUIs keep expanding, using more and more widgets, we start to talk to networks, databases, and graphical libraries that greatly enhance our GUI's functionality. This book is what you need to expand your knowledge on the subject of GUIs, and make sure you're not missing out in the long run.
Style and approach This programming cookbook consists of standalone recipes, and this approach makes it unique.. While each recipe explains a certain concept, throughout the book you'll build a more and more advanced GUI, recipe after recipe. In some of the advanced topics, we simply create a new GUI in order to explore these topics in depth. Dive into GUI application development and create useful applications for practical and relevant topics in the fields of business, computer science, and research.
This book uses a realistic approach to help get you started designing and building the applications you need while learning new tools along the way. PyQt has a vast collection of tools that you can use to create GUIs, many of which seem to go unexplored. In Modern PyQt, you will go beyond some of the fundamental topics of GUI development in order to begin building useful desktop applications.
Through extensive examples and hands-on projects, you will explore how to make applications for data analysis and visualization using graphs, computer vision with OpenCV and PyQt, the basics of networking, handling databases with SQL, and more! Whether you are looking for new ideas to practice your skills as a programmer or you have a specific goal in mind and need some help to get your ideas off the ground, there is something in Modern PyQt for you!
Understand the important PyQt classes, widgets, and concepts needed for building interactive and practical applications. Find out how to embed useful Python modules into your applications to create more advanced GUIs.
Build useful applications that you can improve or make into something completely new with Python and PyQt. Even if they have never used PyQt before, the concepts learned from other toolkits, such as Tkinter or wxPython, can be carried over for developing applications with using PyQt. The Python 2. Although it includes a complete Python language reference section, it is still geared towards those of you who already have some programming experience. This book explains each piece of technology in depth and shows through clear examples why each feature is useful.
This is the manual you've been waiting for -- the one that covers all major Python components without glossing over how the various pieces fit together.