banner



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 and psycopg2 Python libraries. Utilize the python3 -V and pip3 -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

Screenshot of IDLE for Python 3 returning the version number for 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
ii
3
4
5
6
7
viii
9

# import the psycopg2 database adapter for PostgreSQL
from psycopg2 import connect, sql

# for the sys.exit() method telephone call
import sys

# import the Pygame libraries
import pygame
from pygame.locals import *

At this point, if you salve and run the script, you should see the following response from Pygame:

1
2

pygame 1.9.six
How-do-you-do from the pygame community. https://www.pygame.org/contribute.html

Screenshot of a Pygame Python script running in a terminal window

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
2
3
4
5
6
seven
8

# set the DB proper noun, tabular array, and table information to 'None'
table_data = None
db_name = None
table_name = None

# change these globals to match your settings
user_name = "objectrocket"
user_pass = "mypass"

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
ii
three
4
5
6
7
8
9
ten
11
12
xiii
xiv
15

# create a class for the buttons and labels
course Push( ):

# empty list for button registry
registry = [ ]

# selected push (will have outline rect)
selected = None

# pygame RGBA colors
white = ( 255 , 255 , 255 , 255 )
black = ( 0 , 0 , 0 , 255 )
scarlet = ( 255 , 0 , 0 , 255 )
greenish = ( 50 , 205 , 50 , 255 )
light_blue = ( 173 , 216 , 230 , 255 )

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
two
3
four
5
vi
seven
8
9
x
eleven
12
13
xiv
xv
16

# default font colour for buttons/labels is white
def __init__ ( self , name, loc, colour=white):

# add button to registry
self.registry.suspend ( self )

# paramater attributes
self.name = name
cocky.loc = loc
self.color = colour

# text attr for push button
cocky.text = ""

# size of button changes depending on length of text
self.size = ( int ( len ( self.text )*200 ) , 200 )

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
2
3
4
5
6
7
8
9
ten
xi
12

# font.render(text, antialias, color, background=None) -> Surface
self.font = font.return (
self.proper noun + " " + self.text , # display text
True , # antialias on
cocky.color , # font color
self.black # background color
)

# rect for button
self.rect = self.font.get_rect ( )
cocky.rect.10 = loc[ 0 ]
cocky.rect.y = loc[ i ]

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
2
three
four
5
6
7
eight
9
10
11
12
13
14
xv
16
17
eighteen

# part that connects to Postgres
def connect_postgres(db):

# connect to PostgreSQL
print ( "\nconnecting to PostgreSQL" )
try:
conn = connect (
dbname = db,
user = user_name,
host = "localhost" ,
countersign = user_pass
)
except Exception as err:
print ( "PostgreSQL Connect() Mistake:" , err)
conn = None

# return the connection object
return conn

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
2
three
iv
5
6
vii
eight
9
x
11
12
13
14

# role that returns PostgreSQL records
def return_records(conn):

# instantiate a new cursor object
cursor = conn.cursor ( )

# use sql.SQL() to foreclose SQL injection attack
sql_object = sql.SQL (
# laissez passer SQL statement to sql.SQL() method
"SELECT * FROM {} LIMIT 20;"
).format (
# laissez passer the identifier to the Identifier() method
sql.Identifier ( table_name )
)

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
2
iii

effort:
# use the execute() method to put table information into cursor obj
cursor.execute ( sql_object )

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
2
3
4
v
6
7
8
ix
x
11
12

# employ the fetchall() method to return a list of all the data
table_data = cursor.fetchall ( )

# close cursor objects to avoid memory leaks
cursor.close ( )
except Exception as err:

# print psycopg2 error and set table data to None
print ( "PostgreSQL psycopg2 cursor.execute() ERROR:" , err)
table_data = 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
2
3
iv
v

# initialize the pygame window
pygame.init ( )

# alter the explanation/championship for the Pygame app
pygame.brandish.set_caption ( "ObjectRocket PostgreSQL" , "ObjectRocket PostgreSQL" )

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
2
3

# become the OS screen/monitor resolution
max_width = pygame.display.Info ( ).current_w
max_height = pygame.display.Info ( ).current_h

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
2
3
4
five
6

# create a pygame resizable screen
screen = pygame.display.set_mode (
# create a tuple integer object from screen dimensions
( int (max_width*0.55 ) , int (max_height*0.6 ) ) ,
HWSURFACE | DOUBLEBUF| RESIZABLE
)

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.

Screenshot of a Pygame window running with ObjectRocket PostgreSQL App caption

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
2
3
four
v
6
7
8
9
10
11
12
thirteen
14
15
16
17
18
19
twenty
21
22
23
24
25
26
27
28
29
xxx
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fifty
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
seventy
71
72
73
74
75
76
77
78
79
lxxx
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136

#!/usr/bin/python3
# -*- coding: utf-viii -*-

# import the psycopg2 database adapter for PostgreSQL
from psycopg2 import connect, sql

# for the sys.exit() method call
import sys

# import the Pygame libraries
import pygame
from pygame.locals import *

# set up the DB name, table, and table data to 'None'
table_data = None
db_name = None
table_name = None

# change these globals to lucifer your settings
user_name = "objectrocket"
user_pass = "mypass"

# create a grade for the buttons and labels
class Push( ):

# empty listing for push button registry
registry = [ ]

# selected button (will accept outline rect)
selected = None

# pygame RGBA colors
white = ( 255 , 255 , 255 , 255 )
blackness = ( 0 , 0 , 0 , 255 )
cherry = ( 255 , 0 , 0 , 255 )
green = ( l , 205 , 50 , 255 )
light_blue = ( 173 , 216 , 230 , 255 )

# default font color for buttons/labels is white
def __init__ ( cocky , proper noun, loc, colour=white):

# add push button to registry
self.registry.append ( self )

# paramater attributes
self.name = name

self.loc = loc
self.colour = colour

# text attr for push button
self.text = ""

# size of button changes depending on length of text
self.size = ( int ( len ( self.text )*200 ) , 200 )

# font.render(text, antialias, color, background=None) -> Surface
self.font = font.render (
self.name + " " + self.text , # display text
Truthful , # antialias on
cocky.color , # font colour
self.black # background color
)

# rect for push button
self.rect = self.font.get_rect ( )
cocky.rect.ten = loc[ 0 ]
self.rect.y = loc[ 1 ]

# role that connects to Postgres
def connect_postgres(db):

# connect to PostgreSQL
impress ( "\nconnecting to PostgreSQL" )
endeavor:
conn = connect (
dbname = db,
user = user_name,
host = "localhost" ,
password = user_pass
)
except Exception as err:

impress ( "PostgreSQL Connect() Fault:" , err)
conn = None

# return the connection object
return conn

# part that returns PostgreSQL records
def return_records(conn):

# instantiate a new cursor object
cursor = conn.cursor ( )

# use sql.SQL() to foreclose SQL injection attacks
sql_object = sql.SQL (
# pass SQL statement to sql.SQL() method
"SELECT * FROM {} LIMIT 20;"
).format (
# laissez passer the identifier to the Identifier() method
sql.Identifier ( table_name )
)

try:
# use the execute() method to put table data into cursor obj
cursor.execute ( sql_object )

# employ the fetchall() method to return a list of all the data
table_data = cursor.fetchall ( )

# close cursor objects to avoid memory leaks
cursor.close ( )
except Exception as err:

# impress psycopg2 mistake and prepare table information to None
print ( "PostgreSQL psycopg2 cursor.execute() ERROR:" , err)
table_data = None

return table_data

# initialize the pygame window
pygame.init ( )

# alter the caption/championship for the Pygame app
pygame.display.set_caption ( "ObjectRocket PostgreSQL App" , "ObjectRocket PostgreSQL App" )

# become the OS screen/monitor resolution
max_width = pygame.display.Info ( ).current_w
max_height = pygame.brandish.Info ( ).current_h

# create a pygame resizable screen
screen = pygame.display.set_mode (
( int (max_width*0.55 ) , int (max_height*0.6 ) ) ,
HWSURFACE | DOUBLEBUF| RESIZABLE
)

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel