How To Create A Mac App With Python

Python is well known as one of the most beginner-friendly and flexible programming languages. But while Python has a fantastic onboarding experience for even the least experienced new programmers, it is actually more confusing to get to grips with in some other ways. Python is so flexible, that it isn’t immediately apparent what you can do with it.

You can read a ton of tutorials, for example, and still not understand how to make a game in Python, or how to build a web app. In this post, we’re going to discuss how to make a very simple game in Python using Pygame, the popular selection of modules designed to facilitate simple game creation.

A Python script with the extension.spec, this file includes details about how your Python app needs to be packed up. The first time you run PyInstaller on your app, PyInstaller will generate a.

How To Create A Mac App With Python

What is Pygame?

Something that can be tricky for new developers to understand is that programming languages seldom exist in a vacuum. When making an Android app for example, you will not only have to use Java or Kotlin (the two primary programming languages supported by Google) but also the Android SDK. This is the “software development kit” and it contains a host of different libraries, classes, and tools that make Java code work on Android and give it access to the features that are exclusive to mobile platforms.

So it is with Python. Learning Python is not enough to start building things for the most part: you need additional code supplied by other developers in order to make those programs work. In Python, these external tools usually take the form of “modules.” These are small Python programs that perform useful functions that can support your production.

Pygame is one such collection of modules. And as the name suggests, Pygame supplies lots of functions that are useful for game development. That means things like drawing graphics onto the screen and playing sounds. By providing ready-made functions like this, Pygame can save a developer a huge amount of work and streamline the process. Thus, when you ask how to make a game in Python, most people will tell you to use Pygame!

That said, those used to more comprehensive game engines and IDEs like Unity may find Pygame to be somewhat barebones. You won’t find built-in physics or a fancy drag-and-drop interface here! But while this might increase the amount of work for you as a developer, it also liberates you to use your imagination and to approach your game project entirely from scratch.

(This is a good thing, honest!)

Pygame was written by Pete Shinners and was released in 2000. It has been a community project since then and is currently released under the open source free software GNU Lesser General Public License.

How to make a game in Python – A simple first project

I’m going to turn my approach a little on its head for this tutorial. Instead of talking you through a game step-by-step, I’m instead going to give you the code and then we’re going to break down how it all works.

First, make sure you’ve read our basic introduction to Python code:

This will familiarize you with the basics so that you’ll be able to follow along.

You will also need a Python IDE or code editor, which you can learn about here:

Next, you’re going to past the following code. Here’s one I made earlier:

(In a perfect world I’d use snake case for the coordinates, but in all honest I find this much quicker and clearer. And if that meant nothing to you, don’t worry about it!)

How To Create A Mac App With Python

Hit play and you should be greeted with a game that lets you control a little green square around the screen trying to evade a red square. It’s thrilling stuff!

What does all this do?

Congratulations! You just learned how to make a game in Python! Except you probably don’t know what any of this does or why we’ve done it the way we have. So let’s go through it, shall we?

First, we import the Pygame module with the line import pygame. This will likely already be on your machine and probably came as default with your installation. If it didn’t, then you can install it with pip. We also need to initialize Pygame with pygame.init(). Next, we create a window for our game to display in. “Set_caption” lets us give our game a title, displayed at the top of said window.

In the next section, we’re defining a bunch of variables: coordinates for ourselves and the bad guy, a speed for ourselves and the bad guy, and a boolean (true or false value) that tells us whether the game is running or not.

There’s a little function next called drawGame().In here, we are first filling the screen with a blank color (black). Doing this means we can move the position of our characters without leaving behind a trail. Another option would be to draw the characters on top of themselves in black.

This is followed by drawing the two squares. We are placing them inside the window, we are giving them RGB color codes, and then we are setting the X and Y coordinates before adding in width and height. Remember: along the corridor and down the stairs! I thought it made sense to make our bad guy a little bit bigger than the good guy, and to make him scary red!

Finally, we call pygame.display.update(), so that these elements actually get drawn on the screen.

If you aren’t sure what a function is, then check out this nifty little tutorial:

How to create a game loop in Python

The next part of the code is where the real fun happens. This is the “boilerplate” that you’ll likely see in a lot of Pygame creations. Essentially, this is a loop that is going to keep repeating as long as the value of run is set to True.

The first line of this loop adds a short delay. In effect, this is what will set our “framerate” and prevent everything from happening too fast for us to even see!

Basically, everything that we want to happen repeatedly is going to go into loop. The first thing we’re putting here is a bit of code that defines the behavior of our bad guy. This uses if and elif (else, if) statements in order to control the flow of the code. If the value of the player’s coordinates are larger than the bad guy’s coordinates, then the bad guy will move to change this: closing in on our position. Because our characters move a few pixels at a time (as defined by the vel and baddyVel variables), I have added a little room for error.

However, if the coordinates fall within the 10 pixels of our player, then it’s game over! run is set to False, and the program exits the loop. The final statement following the loop quits the game.

It’s still a little ugly though, seeing as the coordinates set the top left corner of the square, not the center. This means the collision detection is extremely wonky, and if you were really making a game, you would do some maths to make sure the game ended if the characters touched at all.

Notice how each time the baddy changes position, we call drawGame() and refresh the canvas.

Finally, we need to get the input from the player and move the player character in accordance with this. Thankfully, Pygame makes this very easy:

How To Create An App

As you may have gathered, the first part of this code also allows the player to exit by clicking the cross button.

Finally, we quit the game once the loop has ended!

This is what we are left with:

It’s not exactly Cyberpunk 2077, but hey at least it’s finished! #burn

Where to go from here

Now you know how to make a game in Python! At least you know how to make moving squares on a screen… But hopefully, this is enough to give you an idea of how Pygame can extend the capabilities of vanilla Python. The rest is just a matter of learning the skills you need to add additional features, until you have something you’re happy with! Check out the official documentation here.

Or, if you want to accelerate your development and learn marketable skills, why not take an online course? This is the fastest way to learn Python properly, and we even have a handy guide to the best online Python courses. Try Coding with Python: Training for Aspiring Developers for just $49.99. Hurry though, as the course is valued around $700.

This is an overview of the best tools and the best resources for buildingdesktop applications in Python.

First things first. You can build great desktop applications in Python, and someare widely used (like Dropbox). But you'll have to find your own way much morethan you would using Microsoft's or Apple's SDKs. The upside is that, with a bitof legwork to package it appropriately, it's quite feasible to write a Pythonapplication that works on all the major platforms.

GUI toolkits

The first thing you'll need to choose is a GUI toolkit.

  • For traditional desktop UIs, Qt is a clear winner. It's powerful, looksnative on all the major platforms, and has probably the biggest community.There are two different Python bindings: PyQtis older and more mature, but it's only free if your application is open source(licensing), whilePySide is newer and more permissivelylicensed (LGPL). I refer to the main Qt docsa lot - the C++ examples mostly translate to Python quite well - but both PyQt's and PySide's docs contain some useful information.Qt Designer isa drag and drop interface to design your UI; you can compile its .ui filesto Python modules with the pyuic command line tool.
  • For attractive, tablet-style interfaces, Kivy is theright choice. It's a fairly young but promising system. If you want to bringyour application to tablets and smartphones, then Kivy is the only optionthat I'm aware of. More info
  • When you want a basic GUI and don't care about aesthetics, Tkinter is asimple option. It's installed as part of Python. Python's own tkinter documentation is rather minimal, but itlinks to a bunch of other resources. This siteis my favourite - it hasn't been updated in years, but then neither has Tkinter(except that in Python 3, you import tkinter rather than import Tkinter).
  • pygame is popular for building simple 2D games. Thereare also frameworks for 3D graphics (pyglet,Panda3d), but I don't know much about them.
  • An increasingly popular option is to write your application as a local webserver, and build the UI in HTML and Javascript. This lets you use Python'slarge ecosystem of web frameworks and libraries, but it's harder to integratewith desktop conventions for things like opening files and window management.CEF Python lets you make a windowfor your application, based on Google Chrome, but I haven't tried that.

A couple of alternatives I wouldn't recommend unless you have a reason to preferthem: GTK is popular on Linux, but itlooks ugly on other platforms. The older pygtkbindings have excellent documentation; the newer PyGObjectsystem, which supports recent versions of GTK and Python, doesn't (though it'sgetting better). wx seems to have a good community, but development is slow,and new projects that could have used it now mostly seem to pick Qt.

Packaging and Distribution

This is probably the roughest part of making an application in Python. You caneasily distribute tools for developers as Python packages to be installed usingpip, but end users don't generally have Python and pip already set up. Pythonpackages also can't depend on something like Qt. There are a number of ways topackage your application and its dependencies:

Making A Python App

  • Pynsist, my own project, makesa Windows installer which installs a version of Python that you specify, andthen installs your application. Unlike the other tools listed here, it doesn'ttry to 'freeze' your application into an exe, but makes shortcuts which launch.py files. This avoids certain kinds of bugs.
  • cx_Freeze is a freeze tool:it makes an executable out of your application. It works on Windows, Mac andLinux, but only produces the executable for the platform you run it on (youcan't make a Windows exe on Linux, for example).It can make simple packages (.msi for Windows, .dmg for Mac, .rpm for Linux),or you can feed its output into NSIS orInno Setup to have more control overbuilding a Windows installer.
  • PyInstaller is similar to cx_Freeze.It doesn't yet support Python 3 (update: it does now, since October 2015),but it does have the ability to produce a 'single file' executable.
  • py2app is a freeze tool specificallyfor building Mac .app bundles.
  • py2exe is a Windows-only freeze tool.Development stopped for a long time, but at the time of writing there is somerecent activity on it.

Linux packaging

Although some of the freeze tools can build Linux binaries, the preferred way todistribute software is to make a package containing just your application, whichhas dependencies on Python and the libraries your application uses. So yourpackage doesn't contain everything it needs, but it tells the package managerwhat other pieces it needs installed.

Unfortunately, the procedures for preparing these are pretty complex, and Linuxdistributions still don't have a common package format. The main ones are debpackages, used by Debian, Ubuntu and Mint, and rpm packages, used by Fedora andRed Hat. I don't know of a good, simple guide to packaging Python applicationsfor either - if you find one or write one, let me know.

You can get users to download and install your package, but if you want it toreceive updates through the package manager, you'll need to host it in arepository. Submitting your package to the distribution's main repositories makesit easiest for users to install, but it has to meet the distro's qualitystandards, and you generally can't push new feature releases to people except whenthey upgrade the whole distribution. Some distributions offer hosting forpersonal repos: Ubuntu's PPAs, or Fedora's Fedorapeople repositories. You canalso set up a repository on your own server.

If you don't want to think about all that, just make a tarball of your application,and explain to Linux users next to the download what it requires.

Miscellaneous

  • Threading: If your application does anything taking longer than about a tenthof a second, you should do it in a background thread, so your UI doesn't freezeup. Be sure to only interact with GUI elements from the main thread, or youcan get segfaults. Python's GIL isn't a big issue here: the UI thread shouldn'tneed much Python processing time.
  • Updates: Esky is a framework forupdating frozen Python applications. I haven't tried it, but it looks interesting.