How To Install Pygame For Python 3.6
Introduction to creating a PostgreSQL GUI app in Python
The Pygame library distribution for Python is substantially a wrapper for the SDL (Unproblematic Directmedia Layer) written in the C and C++ programming languages. Information technology's an like shooting fish in a barrel and elementary way to create games, and other GUI applications, for Window, macOS, and Linux operating systems.
This two-part article series will demonstrate how you can use the psycopg2 Python adapter for PostgreSQL to brand a uncomplicated query GUI desktop awarding, with Pygame, using just 300 lines of code. This article will provide instance code that tin can assistance y'all in setting up the Pygame application, and how you can create a few Psycopg2 Python functions that will display the PostgreSQL database'south table data on the Pygame surface.
Prerequisites to creating a PostgreSQL GUI application using Pygame
- You'll demand to have Python 3 and the PIP3 package managing director for Python installed on your machine before yous tin install the
pygame
andpsycopg2
Python libraries. Utilize thepython3 -V
andpip3 -V
commands in a concluding or command prompt window to bank check if Python 3 and PIP are installed by having them render their respective version numbers.
Install the Pygame library using Python'south PIP3 package manager
- Use the
pip3
command to install the package libraries for the code in these manufactures. Here's how to install Pygame for Python three:
- If you'd like to upgrade your installation of Pygame (this code has been tested in Pygame version
1.9.six
) and then only apply the--upgrade
flag:
1 | sudo python3 -m pip install --upgrade pygame |
Install the psycopg2 Python adapter for PostgreSQL
The last Python package to install for the PostgreSQL application is the psycopg2
adapter Python distribution for PostgreSQL. Here's how y'all can do this with PIP3 for Python:
Create a project folder for the PostgreSQL GUI application
Open up a terminal or command prompt in your projection directory (or just use the mkdir
command to create a directory. In one case since y'all should make a new file for the Python script (using the .py
file extension) and open in it in your IDE or text editor of choice. Ideally you should use an editor that has support for Python syntax and indentation to forestall errors.
Import the necessary Python libraries for Pygame and PostgreSQL
Make sure to import all of the libraries necessary for the Pygame/PostgreSQL GUI application at the get-go of the script. Use the following lawmaking to import them:
1 | # import the psycopg2 database adapter for PostgreSQL # for the sys.exit() method telephone call # import the Pygame libraries |
At this point, if you salve and run the script, you should see the following response from Pygame:
1 | pygame 1.9.six |
Setup globals for the PostgreSQL connection parameters
The commencement bit of really code for the awarding will be to setup some globals for the PostgreSQL connexion:
1 | # set the DB proper noun, tabular array, and table information to 'None' # change these globals to match your settings |
It's possible to only have the user blazon the username and password parameters into the application itself, but, for the sake of brevity, we'll just hard-lawmaking them into the application for now.
Declare a Python form for the Pygame awarding'southward buttons
We'll utilise a Python form constructor for the Pygame buttons and labels to encapsulate and organize all of the necessary attributes and methods. We'll also utilize a registry
list object, in the class itself, to store all of the Push objects and so that we can iterate over the list afterwards.
Declare the Python course and its attributes
The first part of the Button()
class code will be to declare the class and its chief attributes:
i | # create a class for the buttons and labels # empty list for button registry # selected push (will have outline rect) # pygame RGBA colors |
Note: Pygame supports colors with an alpha (transparent) channel, so the 4-chemical element tuple values above represent the RGBA color values (1-255).
The class'due south selected
attribute is for storing a button form attribute that has been clicked on past the user.
Create a constructor for the push methods and attributes
Now we tin create an __init__
constructor for the form button attributes. Make sure to suspend
each aspect to the registry, and to fix the name
, loc
, colour
, and text
attributes like in the following code:
1 | # default font colour for buttons/labels is white # add button to registry # paramater attributes # text attr for push button # size of button changes depending on length of text |
Have each Button() instance inherit the Pygame methods
Concatenate a string that will correspond the text that the button will display inside of the Pygame font.return()
method. This will brand it then that each button case will inherit the Pygame method, and practise the same for the font.get_rect()
method as well:
1 | # font.render(text, antialias, color, background=None) -> Surface # rect for button |
Note: Each button instance will display the button's name and the text value (PostgreSQL database and table parameter) assigned to it.
Define a Python function that will connect to PostgreSQL
At present that we accept a Push button()
class constructor, let's make a part that will endeavor to connect to PostgreSQL using the psycopg2 library'south connect()
method:
one | # part that connects to Postgres # connect to PostgreSQL # return the connection object |
Note: If PostgreSQL is not running, or if the database, username, and password parameters aren't set correctly, then psycopg2 will return an error, and the connexion ( conn
) object will be set to None
.
Create a function that will return records from a PostgreSQL table
The side by side PostgreSQL function volition accept the connection object (returned past the previously defined role in a higher place) and effort to fetch records from a tabular array proper noun specified by the application user.
Here's how you can create a cursor object and so apply the psycopg2 adapter's sql.SQL()
method to concatenate a SQL statement string:
1 | # role that returns PostgreSQL records # instantiate a new cursor object # use sql.SQL() to foreclose SQL injection attack |
Annotation: Considering of the obvious screen existent estate limitations imposed by the GUI application, nosotros'll use an SQL limit clause ( LIMIT 20
) to restrict the number of records returned by the psycopg2 API telephone call to a maximum of 20 rows.
Use a try-except indentation block to grab errors while executing PostgreSQL statements
One time yous've concatenated an sql.SQL
object using the PostgreSQL table name you can laissez passer it to the cursor'southward execute()
method to store the records in the cursor object itself:
1 | effort: |
Fetch the PostgreSQL records from the psycopg2 cursor object
Call the cursor'southward fetchall()
method to return the 20 rows of records from the cursor in the course of a tuple listing and close the cursor in lodge to gratis up the resources:
one | # employ the fetchall() method to return a list of all the data # close cursor objects to avoid memory leaks # print psycopg2 error and set table data to None return table_data |
Notation: Only like the connect_postgres()
part defined before, this one will set the returned object's value to None
in the case of any exceptions. window
Initialize the Pygame application
The last step is to initialize all of the imported Pygame modules using the pygame.init()
method call. Hither's how yous can do that and likewise fix a caption (or title) for the Pygame window:
one | # initialize the pygame window # alter the explanation/championship for the Pygame app |
Apply Pygame to render the native screen resolution
The post-obit code calls the pygame.display.Info()
method to admission its current_w
and current_h
attributes in order to summate the acme and width of the Pygame surface based on the organisation's current screen resolution:
1 | # become the OS screen/monitor resolution |
Declare a new Pygame surface for the PostgreSQL application
The following code creates a Pygame screen (or pygame.Surface
object) for the application window past passing a width and height tuple object consisting of integers (e.1000. (1280, 72)
) to the brandish.set_mode()
method:
ane | # create a pygame resizable screen |
NOTE: The HWSURFACE | DOUBLEBUF| RESIZABLE
values are optional. Include the RESIZABLE
parameter only if you desire the user to exist able to resize the Pygame window.
Conclusion
Test the Python script in a terminal or command prompt window using the python3
command to execute information technology:
You should run into the Pygame application window briefly display for a 2d and and so disappear again.
In the side by side part of this serial we will create a Pygame loop for the application so that the window stays open up, and we'll add the logic for the PostgreSQL function and so that Pygame will display the table rows, returned by the psycopg2 adapter, in the window surface.
Just the Code
1 | #!/usr/bin/python3 # import the psycopg2 database adapter for PostgreSQL # for the sys.exit() method call # import the Pygame libraries # set up the DB name, table, and table data to 'None' # change these globals to lucifer your settings # create a grade for the buttons and labels # empty listing for push button registry # selected button (will accept outline rect) # pygame RGBA colors # default font color for buttons/labels is white # add push button to registry # paramater attributes self.loc = loc # text attr for push button # size of button changes depending on length of text # font.render(text, antialias, color, background=None) -> Surface # rect for push button # role that connects to Postgres # connect to PostgreSQL impress ( "PostgreSQL Connect() Fault:" , err) # return the connection object # part that returns PostgreSQL records # instantiate a new cursor object # use sql.SQL() to foreclose SQL injection attacks try: # employ the fetchall() method to return a list of all the data # close cursor objects to avoid memory leaks # impress psycopg2 mistake and prepare table information to None return table_data # initialize the pygame window # alter the caption/championship for the Pygame app # become the OS screen/monitor resolution # create a pygame resizable screen |
Airplane pilot the ObjectRocket Platform Free!
Endeavour Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started
Source: https://kb.objectrocket.com/postgresql/build-a-postgresql-gui-app-in-python-part-1-872
Posted by: cannadygles1968.blogspot.com
0 Response to "How To Install Pygame For Python 3.6"
Post a Comment