Site Sponsors:
PyGame Example - The Lazy Star 
Had a chance to teach a bunch of wonderful new Python students this month.

Several were interested in using pygame, so we put together the following demonstration.

Thought we would share it.

Note that - before running pygame - that we will need to use pip (or pip3) to install the pygame package (e.g: pip3 install pygame)

Linux folks should install packages using PIP as to get those Super Cow Powers (i.e either su, or sudo should moo nicely.)

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Hackin' Around!")

back_color = (128, 45, 100) # Ubuntu Default

clock = pygame.time.Clock()

def stat(zEvent):
screen.fill(back_color)
if zEvent is None:
return
try:
loc = zEvent.__dict__['pos']
basicfont = pygame.font.SysFont(None, 72)
text = basicfont.render('*', True, (255, 0, 0), back_color)
screen.blit(text, loc)
except Exception as ex:
print("Exceptional:", zEvent)


stat(None)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # closing the window
break
stat(event)
pygame.display.update()
clock.tick(12) # fps
pygame.quit()

Note that 'fps' in the above stands for "frames per second." The lower, the slower. -You can set it to 1000 or so to speed things up ... allot!

Sharing is caring!

-Rn

p.s. If you want to learn more about programing in Python 3, then here is a discount coupon to my on-line training.

[ add comment ] ( 25 views )   |  permalink  |  related link
"Just Do It:" Graphical Command-Line Parameters for Python 3 
There seems to be a huge line between those who want to use console applications, and those who have the need for a GUI.

When using Python however, such lines need not exist: It can be easy to jump between the the Graphical & Textual Worlds!

#!/usr/bin/python3
from tkinter import *


# Mission: Create a way to query a user for command-line values.
# Mission statement implies the encapsulation of a GUI paradigm.
# Here is how to do so using tkinter under Python 3.

''' Prompter: Graphically get a dictionary of command-line strings from a user.
Dictionary result is empty when the `cancel` button has been pressed, else the results
will contain the tag-value pairing (i.e. Dictionary keys match the fields requested, to
get the user's response for each field.)
'''
class Prompter:
def __init__(self):
self._dict = None
self._isOk = None

def _okay(self):
self._isOk = True
self.tk.quit()

def _cancel(self):
self._isOk = False
self.tk.quit()

@staticmethod
def InputStrings(*fields, title="Input"):
self = Prompter()
self.tk = Tk()

self._dict = dict()

if title:
self.tk.title(title)

row = 0
# zFields (A Label, plus an Entry, in a grid layout)
for ref in fields:
obj = Label(master=self.tk, text=str(ref))
obj.grid(row=row, column=0)

obj = Entry(master=self.tk, bd=5)
obj.grid(row=row, column=1)

self._dict[ref]=obj
row = row + 1

# zButtons (A Frame in the grid, plus the properly-centered pair of buttons)
bottom = Frame(self.tk)
bottom.grid(row=row, columnspan=2)
btn = Button(bottom, text="Okay", command=self._okay)
btn.pack(side=LEFT)

btn = Button(bottom, text="Cancel", command=self._cancel)
btn.pack(side=RIGHT)

# zCenter (Close enough to make no odds?)
width = self.tk.winfo_screenwidth()
height = self.tk.winfo_screenheight()
x = width / 2 - (self.tk.winfo_reqwidth() / 2)
y = height / 2 - (self.tk.winfo_reqheight() / 2)
self.tk.geometry("+%d+%d" % (x, y))

self.tk.mainloop()
results = dict()
if self._isOk is not True:
return results

for ref in self._dict.keys():
results[ref] = (self._dict[ref]).get()
return results

if __name__ == "__main__":
# Here is how we would use the Prompter from a Console Program:
results = Prompter.InputStrings("this", "isa", "test", title="Just Do It!")
if len(results) is 0:
print("Pressed Cancel - no values!")
else:
print("Pressed Okay - got values!")
for ref in results:
print(ref, results[ref])

Taking time to review the test case, all one need do is to provide Prompter.InputStrings() with the queries. The title is optional.


Upon activation, Prompter.InputStrings() will create a reasonable-looking user interface, screen-center it & use it to query the user, then return a dictionary of the string response(s) provided.


When the user presses "cancel," the dictionary will be empty.

WIPI Results


Of course, one of the most annoying things about Dict()ionaries in this man's world is - at the time of this writing - the eccentric ordering of their key:value pairs.

Submitted for your perusal therefore, allow me to offer up Prompter.InputOrder() for your more predictable re-usages:

    @staticmethod
def InputOrder(*fields, title="Input"):
results = Prompter.InputStrings(*fields, title=title)
if len(results) is 0:
return [*zip([],[])]
data = []
for ref in fields:
data.append(results[ref])
results = zip(fields, data)
return [*results]

Designed to work exactly as Prompter.InputStrings() (sans the dict(), of course):


-Here be the test case:
    results = Prompter.InputOrder("this", "isa", "test", title="Just Do It!")
if len(results) is 0:
print("Pressed Cancel - no values!")
else:
print("Pressed Okay - got values!")
for ref in results:
print(ref[0], ref[1])
-With the much more predictable, everything is WHERE-I-PUT-IT (W.I.P.I = 'wippy') 'list of lists' result paring:



[ add comment ] ( 192 views )   |  permalink  |  related link
zPython Clock, Revisited 
Here is an upgrade for zClock:



from tkinter import *
import time

zProgram = Tk()
zProgram.title("zPython Clock - Soft9000.com")
zClock = Label(zProgram,
font=('ariel', 72, 'bold'),
bg='gold',
fg='white')

zDay = Label(zProgram,
font=('ariel', 36, 'bold'),
bg='gold',
fg='green')

zDate = Label(zProgram,
font=('ariel', 36, 'bold'),
bg='gold',
fg='blue')

zClock.pack(fill=BOTH, expand=1)
zDay.pack(side='left', fill=X, expand=1)
zDate.pack(side='right', fill=X, expand=1)


def zTimer():
zClock.config(text=time.strftime('%H:%M:%S'))
zDay.config(text=time.strftime('%a'))
zDate.config(text=time.strftime('%m/%d/%y'))
zClock.after(500, zTimer)


zTimer()
zProgram.mainloop()


Here is zVideo :-)


[ add comment ] ( 160 views )   |  permalink  |  related link

| 1 | 2 | 3 | 4 | 5 | Next> Last>>