How to install Pygame using PIP or an IDE
We will see in this tutorial how to install the pygame module on Windows or MAC using pip or the PyCharm editor.
Introduction
When you’re new to Python programming, the best way to improve your skills is to create mini-games. This allows you to have fun while learning the basics of programming. To develop a game in Python, there are several modules that make it easier to work with graphics (such as rectangles, circles, images, etc…) and sounds. Pygame is one of them.
Pygame is a Python wrapper for the SDL (Simple DirectMedia Layer) library. SDL provides cross-platform access to the underlying multimedia hardware components of your system, such as sound, video, mouse, keyboard and joystick. You can therefore program games and Python programs with Pygame that are supported on different platforms.
By default, Pygame is not installed on the Python programming environment. We will therefore see in this guide the best instructions for installing it on your system.
If you wish to deepen your knowledge in the Pygame Module, I invite you to read this book :
As an Amazon Associate I earn from qualifying purchases. If you purchase a product by using a link on this page, I’ll earn a small commission at no extra cost to you
No products found.
How to install Pygame for Windows
Install Python
To run the Pygame module, we must have a version of Python on our machine. If you haven’t already done so, it is available here :
Download Latest Version of Python
Click on the version of Python you are interested in and press download. You can install the latest stable version of Python.
Once the download is complete, press the run button. Check the box ”Add Python 3.5 to PATH”.
Make sure the checkboxes for “Optional features” are checked. For the rest, you can leave them as they are. To finalize the installation, press the install button for your computer to complete the installation.
Install Module Pygame
You can get a version of Pygame via this link :
Take the latest version available and click on the link to download the .whl file to your computer.
pygame‑1.9.6‑cp39‑cp39‑win32.whl
You can choose between a 32bits or 64bits version (in this example, we will start with the win32 version).
To install the previously downloaded Pygame module, we need to access the Windows command line.
To access it, right-click on the started menu and click on Execute. Then type on the text box “cmd“.
Then go to the directory where you installed the Pygame module (by default in the Downloads folder).
Once you are in the right folder, type the following command prompt:
To check that the installation has worked, type the following command prompt:
If you do not see any error messages, the installation went well.
How to install Pygame for OS X
The first step to do is to access the command line. To do so, click on the Spotlight icon and type “terminal” to find it.
We will install XCode (which is an Apple tool for creating Mac and iOS applications. Once the installation is complete, type the following command prompt:
Install Homebrew
Homebrew is a package manager for Mac that simplifies the installation of many different software or packages such as Git, Python or Pygame. Homebrew allows you to avoid possible security issues related to the use of the sudo command to install software like Node.
To install it, copy and paste this on the command prompt:
You will also need to install Homebrew Cask :
Install pygame and these Requirements
To install pygame, we must first install all the pygame dependencies. To do this, please run the following commands one at a time:
As you can see, we have installed python 3 and the pygame module. To check that the installation has been successful, type the following commands:
If you don’t get any error messages, it means that the installation was successful.
How to install Pygame using PyCharm IDE
PyCharm is an integrated development environment (IDE) used in computer programming, specifically for the Python language. PyCharm is cross-platform, with Windows, macOS and Linux versions.
To start opening Pycharm and create a new python project. Then create a python file by right-clicking on the project then New then Python file. Name your python file as you wish.
In your python file, type the following line :
You will see that the pygame is underlined in red. To install pygame, move the mouse over the red underlined area and click on “install package pygame“.
Wait for Pycharm to install pygame and that’s it !
PyCharm IDE : How to install pygame module
Conclusion
In this tutorial, we have seen how to install pygame on Windows, OS X and using an IDE like PyCharm. Now it’s up to you to create your first 2D mini-game!
Here is an example of what you can do with Pygame :
Don’t hesitate to tell me in the comments if you have problems with the pygame installation. And also, I would be happy to see your future projects on pygame!
I’m a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming 🙂
Build a game framework with Python using the Pygame module
In my first article in this series, I explained how to use Python to create a simple, text-based dice game. You also used the Turtle module to generate some simple graphics. In this article, you start using a module called Pygame to create a game with graphics.
The Turtle module is included with Python by default. Anyone who’s got Python installed also has Turtle. The same is not true for an advanced module like Pygame. Because it’s a specialized code library, you must install Pygame yourself. Modern Python development uses the concept of virtual environments, which provides your Python code its own space to run in, and also helps manage which code libraries your application uses. This ensures that when you pass your Python application to another user to play, you know exactly what they need to install to make it work.
You can manage your Python virtual environment manually, or you can let your IDE help you. For now, you can let PyCharm do all the work. If you’re not using PyCharm, read László Kiss Kollár’s article about managing Python packages.
Getting started with Pygame
Pygame is a library, or Python module. It’s a collection of common code that prevents you from having to reinvent the wheel with every new game you write. You’ve already used the Turtle module, and you can imagine how complex that could have been if you’d had to write the code to create a pen before drawing with it. Pygame offers similar advantages, but for video games.
A video game needs a setting, a world in which it takes place. In Pygame, there are two different ways to create your setting:
- Set a background color
- Set a background image
Either way, your background is only an image or a color. Your video game characters can’t interact with things in the background, so don’t put anything too important back there. It’s just set dressing.
Setting up your first Pygame script
To start a new Python project, you would normally create a new folder on your computer and place all your game files go into this directory. It’s vitally important that you keep all the files needed to run your game inside of your project folder.
PyCharm (or whatever IDE you use) can do this for you.
To create a new project in PyCharm, navigate to the File menu and select New Project. In the window that appears, enter a name for your project (such as game_001.) Notice that this project is saved into a special PycharmProjects folder in your home directory. This ensures that all the files your game needs stays in one place.
When creating a new project, let PyCharm create a new environment using Virtualenv, and accept all defaults. Enable the option to create a main.py file (and to set up some important defaults.)
After you’ve clicked the Create button, a new project appears in your PyCharm window. The project consists of a virtual environment (the venv directory listed in the left column) and a demo file called main.py.
Delete all the contents of main.py so you can enter your own custom code. A Python script starts with the file type, your name, and the license you want to use. Use an open source license so your friends can improve your game and share their changes with you:
Then tell Python what modules you want to use. In this code sample, you don’t have to type the # character or anything after it on each line. The # character in Python represents a comment, notes in code left for yourself and other coders.
Notice that PyCharm doesn’t understand what Pygame is, and underlines it to mark it as an error. This is because Pygame, unlike sys and os, isn’t included with Python by default. You need to include Pygame in your project directory before you can use it successfully in code. To include it, hover your mouse over the word pygame until you see a notification popup explaining the error.
Click the Install package pygame link in the alert box, and wait for PyCharm to install Pygame into your virtual environment.
Once it’s installed, the error disappears.
Without an IDE like PyCharm, you can install Pygame into your virtual environment manually using the pip command.
Code sections
Because you’ll be working a lot with this script file, it helps to make sections within the file so you know where to put stuff. You do this with block comments, which are comments that are visible only when looking at your source code. Create four blocks in your code. These are all comments that Python ignores, but they’re good placeholders for you as you follow along with these lessons. I still use placeholders when I code, because it helps me organize and plan.
Next, set the window size for your game. Keep in mind that not everyone has a big computer screen, so it’s best to use a screen size that fits on «most» people’s computers.
There is a way to toggle full-screen mode, the way many modern video games do, but since you’re just starting out, keep it simple and just set one size.
The Pygame engine requires some basic setup before you can use it in a script. You must set the frame rate, start its internal clock, and start (using the keyword init , for initialize) Pygame.
Add these variables:
Add instructions to start Pygame’s internal clock in the Setup section:
Now you can set your background.
Setting the background
Before you continue, open a graphics application and create a background for your game world. Save it as stage.png inside a folder called images in your project directory. If you need a starting point, you can download a set of Creative Commons backgrounds from kenny.nl.
There are several free graphic applications you can use to create, resize, or modify graphics for your games.
-
is a basic, easy to learn paint application. is a professional-level paint materials emulator that can be used to create beautiful images. If you’re very interested in creating art for video games, you can even purchase a series of online game art tutorials. is a vector graphics application. Use it to draw with shapes, lines, splines, and Bézier curves.
Your graphic doesn’t have to be complex, and you can always go back and change it later. Once you have a background, add this code in the setup section of your file:
If you’re just going to fill the background of your game world with a color, all you need is:
You also must define a color to use. In your setup section, create some color definitions using values for red, green, and blue (RGB).
Look out for errors
PyCharm is strict, and that’s pretty typical for programming. Syntax is paramount! As you enter your code into PyCharm, you see warnings and errors. The warnings are yellow and the errors are red.
PyCharm can be over-zealous sometimes, though, so it’s usually safe to ignore warnings. You may be violating the «Python style», but these are subtle conventions that you’ll learn in time. Your code will still run as expected.
Errors, on the other hand, prevent your code (and sometimes PyCharm) from doing what you expect. For instance, PyCharm is very insistent that there’s a newline character at the end of the last line of code, so you must press Enter or Return on your keyboard at the end of your code. If you don’t, PyCharm quietly refuses to run your code.
Running the game
At this point, you could theoretically start your game. The problem is, it would only last for a millisecond.
To prove this, save and then run your game.
If you are using IDLE, run your game by selecting Run Module from the Run menu.
If you are using PyCharm, click the Run file button in the top right toolbar.
You can also run a Python script straight from a Unix terminal or a Windows command prompt, as long as you’re in your virtual environment.
However you launch it, don’t expect much, because your game only lasts a few milliseconds right now. You can fix that in the next section.
Looping
Unless told otherwise, a Python script runs once and only once. Computers are very fast these days, so your Python script runs in less than a second.
To force your game to stay open and active long enough for someone to see it (let alone play it), use a while loop. To make your game remain open, you can set a variable to some value, then tell a while loop to keep looping for as long as the variable remains unchanged.
This is often called a «main loop,» and you can use the term main as your variable. Add this anywhere in your Variables section:
During the main loop, use Pygame keywords to detect if keys on the keyboard have been pressed or released. Add this to your main loop section:
Be sure to press Enter or Return after the final line of your code so there’s an empty line at the bottom of your file.
Also in your main loop, refresh your world’s background.
If you are using an image for the background:
If you are using a color for the background:
Finally, tell Pygame to refresh everything on the screen and advance the game’s internal clock.
Save your file, and run it again to see the most boring game ever created.
To quit the game, press q on your keyboard.
Freeze your Python environment
PyCharm is managing your code libraries, but your users aren’t going to run your game from PyCharm. Just as you save your code file, you also need to preserve your virtual environment.
Go to the Tools menu and select Sync Python Requirements. This saves your library dependencies to a special file called requirements.txt. The first time you sync your requirements, PyCharm prompts you to install a plugin and to add dependencies. Click to accept these offers.
A requirements.txt is generated for you, and placed into your project directory.
Here’s what your code should look like so far:
What to do next
In the next article of this series, I’ll show you how to add to your currently empty game world, so start creating or finding some graphics to use!
Add pygame module in PyCharm IDE
I’ve downloaded pygame-1.9.1release.tar.gz from the Pygame website. I extracted and installed it and it’s working fine in the command line Python interpreter in Terminal (Ubuntu). But I want to install it for some IDE, like PyCharm. How can I do it?
5 Answers 5
Well, you don’t have to download it for PyCharm here. You probably know how it checks your code. Through the interpreter! You don’t need to use complex command lines or anything like that. You need to is:
Download the appropriate interpreter with PyGame included
Open your PyCharm IDE (Make sure it is up to date)
Press Settings (Or Ctrl + Alt + S)
Double click on the option that looks like Project: Name_of_Project
Click on Project Interpreter
Choose the interpreter you want to use that includes PyGame as a module
Save your options
And you are ready to go! Here is an alternate (I have never done this, please try to test it)
- Add PyGame in the same folder as your PyCharm file (Your PyCharm stuff is always in a specific file placed by you during installation/upgrade) Please consider putting your PyCharm stuff inside a folder for easy access.
I hope this helps you!
For PyCharm 2017 do the following:
- File — Settings
- Double click on your project name
- Select Project Interpreter
- Click on green + button on the right side of the window
- Type Pygame in search window
- Click Install package.
Not I’m saying that the answers above won’t work, but it might be frustrating to a newbie to do command line magic.
If you are using PyCharm and you are on a Windows 10 machine use the following instructions:
Click on the Windows start menu and type cmd and click on the Command Prompt icon.
Use the command pushd to navigate to your PyCharm project which should be located in your user folder on the C:\ drive. Example: C:\Users\username\PycharmProjects\project name\venv\Scripts.
(If you are unsure go to the settings within PyCharm and navigate to the Python Interpreter settings. This should show you the file path for the interpreter that your project is using. Credit to Anthony Pham for instructions to navigate to interpreter settings.)
HINT: Use copy and paste in the command prompt to paste in the file path.
Use the command pip install pygame and the pip program will handle the rest for you.
Restart you Pycharm and you should now be able to import pygame
Hope this helps. I had a fun time trying to find out the correct way to get it installed, so hopefully this helps someone out in the future.
Добавить модуль pygame в PyCharm IDE
Я загрузил pygame-1.9.1release.tar.gz с сайта Pygame. Я извлек и установил его, и он отлично работает в интерпретаторе командной строки Python в терминале (Ubuntu). Но я хочу установить его для некоторых IDE, таких как PyCharm. Как я могу это сделать?
4 ответа
Ну, вам не нужно загружать его для PyCharm здесь. Вероятно, вы знаете, как он проверяет ваш код. Через переводчика! Вам не нужно использовать сложные командные строки или что-то в этом роде. Вам нужно:
Загрузите соответствующий интерпретатор с включенным PyGame
Откройте свою среду разработки PyCharm (убедитесь, что она актуальна)
Перейдите к File
Нажмите Settings (или Ctrl + Alt + S)
Дважды щелкните по опции, которая выглядит как Project: Name_of_Project
Нажмите Project Interpreter
Выберите интерпретатор, который вы хотите использовать, чтобы включал PyGame в качестве модуля
Сохраните ваши параметры
И ты готов к работе! Вот альтернатива (я этого никогда не делал, попробуйте проверить)
- Добавьте PyGame в ту же папку, что и файл PyCharm (ваши файлы PyCharm всегда находятся в папке определенный файл, помещенный вы во время установки/обновления) Пожалуйста, рассмотрите возможность размещения файлов PyCharm внутри папки для удобства доступа.
Надеюсь, это поможет вам!
Для PyCharm 2017 выполните следующие действия:
- Файл — Настройки
- Дважды щелкните имя вашего проекта
- Выберите «Переводчик проекта»
- Нажмите зеленую кнопку + в правой части окна.
- Введите Pygame в окне поиска
- Нажмите «Установить пакет».
Не говорю, что ответы выше не сработают, но новичок может напасть на магию командной строки.
Я просто понял это!
- Поместите файл .whl в C:\Program Files\Anaconda3
- В папке щелкните синюю вкладку Файл в верхнем левом углу окна Explorer (при условии, что вы используете Windows)
- Нажмите Откройте Windows PowerShell как администратор
- Напишите или просто скопируйте и вставьте: py -m pip install pygame
- Он должен начать установку
- Готово!
Я надеюсь, что это сработает для вас. Я знаю, что это было для меня.
Если вы используете PyCharm и на компьютере с Windows 10 используете следующие инструкции:
Нажмите в меню «Пуск» Windows и введите cmd и нажмите значок «Командная строка».
Используйте команду pushd для перехода к вашему проекту PyCharm, который должен быть расположен в вашей папке пользователя на диске C: \. Пример: C:\Users\имя_пользователя\PycharmProjects\имя проекта \venv\Scripts.
(Если вы не уверены, перейдите к настройкам в PyCharm и перейдите к настройкам интерпретатора Python, это покажет вам путь к файлу для интерпретатора, который использует ваш проект. Обратитесь к Энтони Фам за инструкциями по переходу на настройки интерпретатора. )
СОВЕТ. Используйте копию и вставьте в командной строке, чтобы вставить путь к файлу.
Используйте pygame для установки команды pip, и программа pip будет обрабатывать остальное для вас.
Перезапустите Pyyarm, и теперь вы сможете импортировать pygame
Надеюсь, это поможет. Мне было весело, пытаясь найти правильный способ установить его, поэтому, надеюсь, это поможет кому-то в будущем.