PythoFF

Menu

Sign in:

read us on

home/2019/01/30/92e0b5c09d74ec8fae7e8b3daaf0d932949d5862.jpg

Python "for" Loops (Definite Iteration)

In this introductory tutorial, you'll learn all about how to perform definite iteration with Python for loops. You’ll see how other programming languages implement definite iteration, learn about iterables and iterators, and tie it all together to learn about Python’s for loop.

home/2019/01/29/25440f809b5f323929d8ed4379d55f5c14a065ec.jpg

Python 201 and Python RegEx Bundle

I recently had the opportunity to partner with Sundeep Agarwal, the author of Python re(gex)? to create a bundle with my second book, Python 201: Intermediate Python. The Python Regex book covers Regular Expressions in Python. While only 50 pages in length, it has lots of examples that you can use to learn all about using Regular Expressions in your own code. You can check out the Github repo and see what kind of code is in the book. You can find the bundle on Leanpub.

home/2019/01/29/477507ac19132b545494db911d15d46424bd9d4b.jpg

wxPython Applications Book Table of Contents Update

I am currently working on a new book entitled Creating GUI Applications with wxPython that you can support on Kickstarter. This is the current table of contents for the book: Chapter 1 – Intro to wxPython Chapter 2 – Creating an Image Viewer Chapter 3 – Enhancing the Image Viewer Chapter 4 – Creating a Database Viewer Chapter 5 – Database Editing with wxPython Chapter 6 – Calculator Chapter 7 – Archiver (tarball creation utility) Chapter 8 – MP3 Tag Editor Chapter 9 – XML Editor Chapter 10 – NASA Image Downloader / Search Tool Chapter 11 – PDF Merger / Splitter There will also be a chapter on creating executables and installers for your application and a couple of appendixes. I am doing a second stretch goal to add up to 3 additional chapters to the book. Check out the Kickstarter for more information.

home/2019/01/29/034d249b647dc3e39a5d262ea6ddfa0f3e25fcde.jpg

Защита микросхем от реверс-инжиниринга и несанкционированного проникновения

“CVAX — когда вы забатите довольно воровать настоящий лучший”. Надпись, оставленная американскими инженерами для советских коллег в топологии микропроцессора. Реверс-инжиниринг микросхем — головная боль производителей с самых первых лет существования микроэлектроники. Вся советская электроника в какой-то момент была построена на нем, а сейчас с гораздо большим размахом тем же самым занимаются в Поднебесной, да и не только в ней. На самом деле, реверс-инжиниринг абсолютно легален в США, Евросоюзе и многих других местах, с целью (цитирую американский закон) “teaching, analyzing, or evaluating the concepts or techniques embodied in the mask work or circuitry”. Самое частое легальное применение реверс-инжиниринга — патентные и лицензионные суды. Промышленный шпионаж тоже распространен, особенно с учетом того, что электрические схемы (особенно аналоговые) часто являются ключевой интеллектуальной собственностью и редко патентуются — как раз для того, чтобы избежать раскрытия IP и участия в патентных судах в качестве обвиняющей стороны. Разумеется, оказавшись в ситуации, когда нужно защитить свою интеллектуальную собственность, не патентуя ее, разработчики и производители стараются придумать способы предотвращения копирования своих разработок. Другое не менее (а то и более) важное направление защиты микросхем от реверс-инжиниринга — обеспечение безопасности информации, хранимой в памяти. Такой информацией может быть как прошивка ПЛИС (то есть опять-таки интеллектуальная собственность разработчика), так и, например, пин-код от банковской карты или ключ шифрования защищенной флэшки. Чем больше ценной информации мы доверяем окружающему миру, тем важнее защищать эту информацию на всех уровнях работы обрабатывающих ее систем, и хардварный уровень — не исключение.

home/2019/01/28/43bc08c10699953933c29f0bc28cafd8f8f844fe.jpg

Jupyter Notebook: An Introduction

In this step-by-step Python tutorial, you learn how to get started with The Jupyter Notebook, an open source web application that you can use to create and share documents that contain live code, equations, visualizations, and text.

PyDev of the Week: Lorena Mesa

This week we welcome Lorena Mesa (@loooorenanicole) as our PyDev of the Week! Lorena is an organizer for the PyLadies Chicago group and a director at the Python Software Foundation. You can check out some of the things that she is up to on her blog or via her Github page. Let’s spend a few moments getting to know her better! Can you tell us a little about yourself (hobbies, education, etc): Hmmm … I have been told that I’m a bit eclectic. So let’s start with the basics, in my day to day gig I am a proud member of GitHub’s software intelligence systems team as a data engineer. In my etc hours I do such things as co-organize PyLadies Chicago and serve as a Director for the Python Software Foundation. Things I do for fun? I’m an avid runner having taken on the Chicago Marathon 13 times now. Why? I encourage you to read Haruki Murakami’s “What I talk about when I talk about running” before you ask me that.Jazz, italo disco, and loud 1980s ballads are equal parts guilty pleasure for me. Meaning of course I’ve been learning the sax and getting pretty good at it lately. (Yes, I can play Careless Whispers).I’m learning Klingon – https://www.kli.org/. You can find my random musings when I post on my personal blog at lorenamesa.com on such things as traveling, tech, and other tidbits. Continue reading PyDev of the Week: Lorena Mesa →

Python 101: Episode #43 Creating Executables with PyInstaller

In this screencast, we will learn how to turn your Python code into a Windows executable file using the PyInstaller project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101

Ищем свободное парковочное место с Python и глубоким обучением

Рассказывает Адам Гейтджи, разработчик в LinkedIn Learning

home/2019/01/23/0c046000b9745e3f138b0aacb2ff72ea8d92d5b6.jpg

Проверка корректности адресов в памяти на Cortex-M0/M3/M4/M7

Привет, Хабр! По поводу случившегося на днях послабления режима, возмущения в комментариях одного соседнего поста о том, что статьи про микроконтроллеры — сплошь мигание светодиодом, а также безвременной гибели моего стандалон-блога, восстанавливать который мне пока лень, переложу сюда полезный материал об одном прискорбно мало освещаемом прессой трюке в работе с ядрами Cortex-M — проверке произвольных адресов на валидность. Одна из весьма полезных и при этом почему-то в готовом виде нигде не описанных возможностей на микроконтроллерах Cortex-M (всех) — это возможность проверки корректности адреса в памяти. С её помощью можно определять размеры флэша, ОЗУ и EEPROM, определять наличие на конкретном процессоре конкретной периферии и регистров, прибивать упавшие процессы при сохранении общей работоспособности ОС и т.п.

home/2019/01/23/3a84334f8d6d77e26a5141a24256ed33c6c06b65.jpg

Python’s Requests Library (Guide)

In this tutorial on Python's "requests" library, you'll see some of the most useful features that requests has to offer as well as how to customize and optimize those features. You'll learn how to use requests efficiently and stop requests to external services from slowing down your application.

home/2019/01/22/477507ac19132b545494db911d15d46424bd9d4b.jpg

Sample Chapters from Creating wxPython Applications Book

The Kickstarter campaign for my latest book has been going quite well, so I thought it would be fun to share some sample chapters of the book with you. You can check out the first couple of chapters here as a PDF. I have also been doing some experiments with regards to some of the ideas that were given about other chapters for the book for the stretch goals of the Kickstarter. I haven’t made any concrete decisions as of yet, but I do think that interacting with the NASA website’s API sounds fun and appears easy to do as well. I will research the feasibility of the other ideas too. Thanks so much for your support!

home/2019/01/21/db57ee30d8aa1732c565581bdcbd49d402b5ddd7.jpg

Working With Files in Python

In this tutorial, you'll learn how you can work with files in Python by using built-in modules to perform practical tasks that involve groups of files, like renaming them, moving them around, archiving them, and getting their metadata.

PyDev of the Week: Nina Zakharenko

This week we welcome Nina Zakharenko (@nnja) as our PyDev of the Week! Nina has been active in the Python community for several years and has spoken or keynoted dozens of conferences. She has also contributed to the Python core language! If you’d like to see what she is up to, check out her blog. Let’s spend a few moments getting to know Nina! Can you tell us a little about yourself (hobbies, education, etc): I’m embarrassed to admit it, but the mid-90s cyberpunk movie Hackers – about a group of hackers framed for deploying a world-threatening computer virus – inspired me to become a programmer at a very young age. Even more embarrassing – I owned a pair of rollerblades growing up. When I was 12, I learned HTML to make websites by reading and deconstructing the source code of sites I visited, and I slowly became more engrossed in technology. As an adult, I studied Computer Science in college, and since then I’ve held a variety of exciting jobs at companies like HBO writing software for satellite control computers, to working for companies like Meetup and at Reddit. This spring, I joined the incredible Cloud Developer Advocacy team at Microsoft as the first Advocate entirely devoted to Python. I love teaching and public speaking. In my spare time I like to snowboard, hike, travel, and tinker with microcontrollers and wearable electronics, such as these Python powered earrings. I tweet at @nnja and occasionally blog and post my talks at nnja.io. Why did you start using Python? I started using Python in 2012 for small scripts and internal tools and eventually started using Python to work on the meetup.com API. In 2013 I went to my first PyCon in Santa Clara. Back then, I was writing Java full-time. I was afraid that I’d get made fun of at the conference for being new to Python, but the opposite was true. So many members of the community welcomed me with open arms. I was totally blown away. I also realized that Python was for so much more than scripting – that it was a powerful first-class language used by some of the top companies in the world. Eventually, I quit my job as a Java Developer and spent a summer at the Recurse Center (known then as Hacker School, a developer retreat in NYC). I focused on learning new tools and languages, dabbling with machine learning, and teaching myself Python. At the Recurse Center, I was able to fall in love with programming all over again. Presently I’ve been writing Python professionally for five years for a variety of companies. The work is much more interesting, and the brevity of whitespace, naming conventions, and simplicity was a breath of fresh air after the verbosity of Java. What other programming languages do you know and which is your favorite? Professionally I’ve been lucky enough to work in a wide variety of languages, frameworks, and technologies. At various points in my career, I’ve been paid to write C++, Javascript, Java, Python, and Clojure. I’ve briefly dabbled in Go, Lisp, Haskell, and Octave for fun. Despite all my experience, Python is still hands down my favorite. It’s just fun to write, fun to learn, and is an exceptionally powerful teaching tool. No matter how long I work in it, I feel like there’s always more to learn. What projects are you working on now? Since starting as a developer advocate, I’m no longer in a position where I work on several large codebases. Instead, I’m working on a ton of different projects. I got my first (tiny) patch accepted into CPython while sprinting with Łukasz Langa at PyCon, and plan on working with a mentor to continue contributing to CPython in the future. I’ve been expanding and contributing to a project called loco to help bring our mostly remote team together, by displaying where in the world someone on the team is at during any given time. I’ve also been working on software and tools that take advantage of Azure and its Python friendly offerings, like Python serverless functions, or deploying web apps on Linux to App Service, a highly scalable, self-patching web hosting service. Which Python libraries are your favorite (core or 3rd party)? In no particular order: ipdb — all the usefulness of the pdb debugger, but bonus features like tab completion and syntax highlighting! ipython — ipython is a powerful interactive shell, complete with nice-to-have features missing from the default Python interactive interpreter such as excellent tab completion, the ability to easily edit classes and functions when editing via the up arrow, and magic functions that allow you to do things like paste chunks of code, open a full-fledged editor, or export your history. black – black is the uncompromising Python code formatter. It’s a tool with practically no configuration options, so it removed any room for ambiguity. I love using the black formatter alongside the [Python extension for VS Code](https://code.visualstudio.com/docs/languages/python?WT.mc_id=none-none-ninaz). micropython – MicroPython is an efficient implementation of Python 3 that includes a small subset of the standard library. The codebase is small enough to run on microcontrollers and can be used for incredible and educational electronics projects. azure cli – the azure cli is a suite of command line tools for Azure, written in Python. [Learn more about it](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest&WT.mc_id=none-none-ninaz), or contribute back to the [open source project](https://github.com/Azure/azure-cli). agithub – makes it so easy to prototype when working with a RESTful API. The project is looking for help and contributions. If you’re interested in getting started with open source, it’s a great opportunity. How did you get started as a conference speaker on Python / tech topics There’s a funny story behind how I got started that involves some mischievous friends. My second Python conference was PyCon Canada in 2013. I was chatting with friends about how impressed I was with the speakers, and how I wished I would have the nerve to speak on stage one day. I had presented my projects at a handful of local meetups, but never to such a large audience. At the conference, my friends found out that someone had dropped out of a lightning talk that was happening within in the next hour. They wrote my name down in the empty slot, and told me I had an hour to put some slides together and get a 5-minute talk ready. I was so nervous! I shook with fear throughout the whole thing, and could barely breathe. When it was over, I realized that it wasn’t so bad. I got through it. The following year I spoke at DjangoCon 2014, followed by PyCon 2015 on technical debt. The talk went very well and was wildly popular. Since then, I’ve spoken at and keynoted dozens of conferences all over the world. That little voice in my head held me back and told me that I wasn’t a good public speaker, that I didn’t have anything to say, that everyone in the room knew more than me. It was a total fallacy, a myth I had perpetuated myself. Public speaking, like everything else in life, is something that you get better at with practice. Do you have any advice for people who want to speak at conferences or user groups? My advice is – Don’t be afraid to throw your hat into the ring. “I have nothing new to say, it’s all been covered” is a myth that I hear beginners perpetuate as a way to talk themselves out of speaking. That’s just not true. Just because a topic has been covered in a talk before doesn’t mean it’s off-limits. What an audience is genuinely interested in is your unique perspective, your story, and the way you tell it. Storytelling is as much a part of a great talk as technical knowledge. Brandon Rhodes is one of the best storytellers in our community, and his talks are a great resource for becoming familiar with the technique. Some of the most interesting talks center on how you came upon a problem, the steps (especially incorrect ones!) taken in an attempt to fix it, and how you finally came to the correct solution. Just like a regular story, it has a beginning, a middle, and an end. If you find large stages intimidating, start small at local meetups or events, or even in front of one or two friends. Lastly, don’t be afraid of rejection. Submit as many CFPs as you can. Always ask for feedback on rejected talks, and use those suggestions to improve your proposals and try again at other events. Rejection stings, but don’t take it personally. Dust yourself off and try again. Second, many conferences offer scholarships to folks underrepresented in tech, both to attendees and to speakers. If you need financial assistance, don’t be afraid to ask and use that opportunity. If you’re on the opposite side of that coin and you or your company are in a position to, some conferences allow you to pay extra for a ticket to sponsor a diversity ticket, or to sponsor the conference itself. Accepting and welcoming diversity in age, gender, race, ability, experience, ethnicity, and many other factors is the future of our industry, and where fresh new ideas will come from. Our community grows stronger when we’re accepting and welcoming to other people. Is there anything else you’d like to say? I’ve been lucky enough to have the opportunity to be mentored throughout my career by an incredible group of caring people. I’m now in a position to do the same. If you’re an underrepresented person in tech and you need advice, help, or mentorship, my [twitter DMs](https://twitter.com/nnja) are open. I’m happy to talk about a wide variety of topics – imposter syndrome, career advice, tech help, help preparing a CFP or working on a talk, or walking through code. If I’m not able to help you, I’ll do my best to connect you with someone who can. If you’d like to hear more about my thoughts on mentorship, you can catch me as a guest on episode 44 of the Test and Code podcast. Thanks for doing the interview, Nina!

Качественно новый уровень визуализации данных в Python

Рассказывает Уилл Кёрсен, data scientist в Cortex Intel

home/2019/01/17/22d64516d8899a1de6948857614a417e452d3e50.jpg

Tornado vs Aiohttp: путешествие в дебри асинхронных фреймворков

Привет! Я Дима, и я довольно давно и плотно сижу на Python. Сегодня хочу показать вам отличия двух асинхронных фреймворков — Tornado и Aiohttp. Расскажу историю выбора между фреймворками в нашем проекте, чем отличаются корутины в Tornado и в AsyncIO, покажу бенчмарки и дам немного полезных советов, как забраться в дебри фреймворков и успешно оттуда выбраться.

home/2019/01/16/b841af8c938beee1af14181040509d9d93665ef3.jpg

Async IO in Python: A Complete Walkthrough

This tutorial will give you a firm grasp of Python’s approach to async IO, which is a concurrent programming design that has received dedicated support in Python, evolving rapidly from Python 3.4 through 3.7 (and probably beyond).

ARM Assembler Editor: Если гора не идет к Магомеду, Магомед идет к горе…

Если кто не знает мне интересно программирование на ассемблере для микроконтроллеров STM32… И все бы хорошо, да только программировать особо негде… Те среды которые есть в настоящий момент заточены больше для языка Си и программирование в них на ассемблере не сильно отличается от программирования в блокноте, ну может быть только многооконность удобна, да еще компиляция (если настроить все так как любит среда). Некоторое время назад (всего 2 года прошло) я сетовал о том что нужен программист для ее написания, но дело с тех пор не сдвинулось… Поэтому вспомнив знаменитую поговорку: «Если гора не идет к Магомеду, Магомед идет к горе» — решил в итоге начать писать самостоятельно… Дальше под катом (будут картинки!!)

Python 101: Episode #42 – Creating Executables with cx_Freeze

In this screencast, we will learn how to turn your Python code into a Windows executable file using the cx_Freeze project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101

home/2019/01/14/673938e6d1b05e05dcdf05cff298f9906cfe4636.jpg

Как не продолбать пароли в Python скриптах

Хранение паролей всегда было головной болью. В классическом варианте у вас есть пользователь, который очень старается не забыть жутко секретный «qwerty123» и информационная система, которая хранит хеш от этого пароля. Хорошая система еще и заботливо солит хеши, чтобы отравить жизнь нехорошим людям, которые могут украсть базу с хешированными паролями. Тут все понятно. Какие-то пароли храним в голове, а какие-то засовываем в зашифрованном виде в keepass. Все меняется, когда мы убираем из схемы человека, который старательно вводит ключ с бумажки. При взаимодействии двух информационных систем, на клиентской стороне в любом случае должен храниться пароль в открытом для системы виде, чтобы его можно было передать и сравнить с эталонным хешем. И вот на этом этапе админы обычно открывают местный филиал велосипедостроительного завода и начинают старательно прятать, обфусцировать и закапывать секретный ключ в коде скриптов. Многие из этих вариантов не просто бесполезны, но и опасны. Я попробую предложить удобное и безопасное решение этой проблемы для python. И чуть затронем powershell.

home/2019/01/14/832749d299a3c72c4efb1d4254c7e6985646107d.jpg

Speed Up Your Python Program With Concurrency

In this Python tutorial, we'll look at what concurrency is and why you might want to use it. We'll see a simple, non-concurrent approach and then look into why you'd want threading, asyncio, or multiprocessing.

Creating GUI Applications with wxPython Kickstarter

I am pleased to announce my latest book project, Creating GUI Applications with wxPython which I am running a Kickstarter campaign for. Creating GUI Applications with wxPython is a book that will teach you how to use wxPython to create applications by actually creating several mini-programs. I have found that while learning how the various widgets work in wxPython is valuable, it is even better to learn by creating a simple application that does something useful. The code in this book will be targeted for Python 3 only using wxPython 4. For more information, please check out the Kickstarter.

PyDev of the Week: Lance Bragstad

This week we welcome Lance Bragstad (@LanceBragstad) as our PyDev of the Week! Lance is a core developer of the OpenStack project. You can find out more about his passions via his website or his Github profile. Let’s spend some time getting to know Lance! Can you tell us a little about yourself (hobbies, education, etc): In 2012, I graduated with a degree in Computer Science from North Dakota State University, located in Fargo (yup, like the movie). Since then I’ve become more and more passionate about open-source software. I spend most of my time in the OpenStack ecosystem. Besides being passionate about open-source software, I’m an avid outdoorsman. My wife and I train for running events together. I also donate time as a volunteer firefighter for our community of about 700 people. Continue reading PyDev of the Week: Lance Bragstad →

home/2019/01/14/83e6f3e60d87ed6e078808edb300e319b8587fc0.jpg

«Теория Большого взрыва» и практика применения Python

Вступление В последнее время активно изучаю язык программирования Python. Особенно меня заинтересовало использование Python в распознавании и классификации лиц. В статье я попробую применить распознавание лиц для сериала «Теория Большого взрыва».

home/2019/01/13/55f35fcdd9cb3ebe40263593af85a08f856267d6.jpg

Introduction to Ansible video course released!

Check out the just-launched video course, Introduction to Ansible on Talk Python Training. This is the perfect course for you if you want to learn to configure servers and deploy web apps... (read more)

home/2019/01/09/30f948568fa601cee2c279e454c23ba56603b7b4.jpg

Django Migrations: A Primer

In this tutorial, you’ll get comfortable with Django migrations and learn how to create database tables without writing any SQL, how to automatically modify your database after you changed your models, and how to revert changes made to your database.

Python 101: Episode #40 – Creating Executables with bbfreeze

In this screencast, we will learn how to turn your Python code into a Windows executable file using the bbfreeze project. You can also read the chapter this video is based on here or get the book on Leanpub Python 101 Related Reading A bbfreeze Tutorial – Build a Binary Series!

home/2019/01/07/78798d3c858be49cc50edb9c91763d824dcacf87.jpg

The Ultimate Guide to Python Type Checking

In this guide, you'll look at Python type checking. Traditionally, types have been handled by the Python interpreter in a flexible but implicit way. Recent versions of Python allow you to specify explicit type hints that can be used by different tools to help you develop your code more efficiently.

PyDev of the Week: Kushal Das

This week we welcome Kushal Das (@kushaldas) as our PyDev of the Week! Kushal is a core developer of the Python programming language and a co-author of PEP 582. You can learn more about Kushal by checking out his blog or his Github profile. Let’s take a few moments to get to know Kushal better! blog Can you tell us a little about yourself (hobbies, education, etc): I am a staff member of Freedom of the Press Foundation. We are a non-profit that protects, defends, and empowers public-interest journalism in the 21st century. We work on encryption tools for journalists and whistleblowers, documentation of attacks on the press, training newsrooms on digital security practices, and advocating for the the public’s right to know. I am also part of various Free Software projects through out my life. I am a core developer of CPython, and a director of the Python Software Foundation. I am part of the core team of the Tor project. I am a regular contributor to Fedora Project for over a decade now. I co-ordinate https://dgplug.org along with a large group of friends and fellow contributors in various projects. We spend time together in learning new things and helping out each other on the #dgplug IRC channel on Freenode server. Feel free to visit the channel and say “Hi” to us. I try to write about the things I learn regularly on my blog. Continue reading PyDev of the Week: Kushal Das →

wxPython: Changing Custom Renderers for Columns / Rows

The wxPython GUI toolkit has a very rich and powerful Grid widget that I have written about previously on this blog. It allows you to create sheets of cells similar to those in Microsoft Excel. There is also a neat mixin that allows you to apply a custom renderer to the labels on the columns and rows of the grid. Let’s take a look at that and see how it works: import wx import wx.grid as grid import wx.lib.mixins.gridlabelrenderer as glr   class MyGrid(grid.Grid, glr.GridWithLabelRenderersMixin):   def __init__(self, *args, **kw): grid.Grid.__init__(self, *args, **kw) glr.GridWithLabelRenderersMixin.__init__(self)   class MyColLabelRenderer(glr.GridLabelRenderer):   def __init__(self, bgcolor): self._bgcolor = bgcolor   def Draw(self, grid, dc, rect, col): dc.SetBrush(wx.Brush(self._bgcolor)) dc.SetPen(wx.TRANSPARENT_PEN) dc.DrawRectangle(rect) hAlign, vAlign = grid.GetColLabelAlignment() text = grid.GetColLabelValue(col) self.DrawBorder(grid, dc, rect) self.DrawText(grid, dc, rect, text, hAlign, vAlign)   class MyPanel(wx.Panel):   def __init__(self, parent): wx.Panel.__init__(self, parent)   grid = MyGrid(self, size=(100, 100)) grid.CreateGrid(numRows=10, numCols=10)   for col in range(0, 10, 3): grid.SetColLabelRenderer( col+0, MyColLabelRenderer('#e0ffe0')) grid.SetColLabelRenderer( col+1, MyColLabelRenderer('#e0e0ff')) grid.SetColLabelRenderer( col+2, MyColLabelRenderer('#ffe0e0'))   main_sizer = wx.BoxSizer(wx.VERTICAL) main_sizer.Add(grid, 1, wx.EXPAND) self.SetSizer(main_sizer)   class MyFrame(wx.Frame):   def __init__(self): wx.Frame.__init__(self, None, title='Custom Grid Renderers') panel = MyPanel(self) self.Show()   if __name__ == '__main__': app = wx.App(False) frame = MyFrame() app.MainLoop() Let’s break this down a bit. You will notice at the top of the code that we need to import the Grid widget separately in wxPython. We also need to import a mixin called GridWithLabelRenderersMixin. We subclass the Grid class and add in the mixin and then initialize both. Next we create a subclass of GridLabelRenderer, which is also from the mixin. This allows us to create a spacing Draw method that will give us the ability to apply different colors or fonts to the labels in our Grid. In this case, I just made it so that we could change the color of the text in the labels. The last piece of code that we are interested in is in the MyPanel class where we actually instantiate the Grid and change the color of the background of the labels in the columns. Here is what the grid ended up looking like: Custom Grid Column Renderers Wrapping up The wxPython toolkit has dozens of pre-built widgets that you can use to create cross-platform user interfaces. The wxPython demo has a much more involved example than this article does that you might also find interesting. If you haven’t given wxPython a try, you really should go get it. It is pip installable from PyPI and compatible with Python 3.

Python 101: Episode #40 – Creating Executables with py2exe

In this screencast, we will learn how to turn your Python code into a Windows executable file using py2exe. You can also read the chapter this video is based on here or get the book on Leanpub Python 101

Older Posts