2- |
Python
program, all information Display to the
screen |
|
|
|
|
|
- Python program, all
information Display to the screen
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
py-merkletree
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
py-merkletree
- Projct
Folder: C:\Users\...\source\repos\py-merkletree
- Startup
File: py-merkletree.py
- Project
file: py-merkletree.sln
|
- Download Python
Project : py-merkletree.zip -
(9.5 KB zip file) Download
- Project
consist of:
One Python Form -
(py-merkletree.py )
|
 | |
Download Python
Project : py-merkletree.zip -
(9.5 KB zip file) Download
|
- Source Code:
Download this Source Code at
python file: py-merkletree.py
- (2.5 KB Python file)
download
|
 |
Continue
|
Python Code,
to display all information Display to the
screen -
(python file :1.py) | |
|
|
"""
all information Display to the screen
"""
from typing import List
import typing
import hashlib
#Create a node (leaf) class and some methods
class Node:
def __init__(self, left, right, value:
str,content)-> None:
self.left: Node = left
self.right: Node = right
self.value = value
self.content = content
@staticmethod
def hash(val: str)-> str:
return hashlib.sha256(val.encode("utf-8")).hexdigest()
def __str__(self):
return(str(self.value))
#Create a MerkleTree class
class MerkleTree:
def __init__(self, values: List[str])-> None:
self.__buildTree(values)
def __buildTree(self, values: List[str])-> None:
leaves: List[Node] = [Node(None, None,
Node.hash(e),e) for e in values]
if len(leaves) % 2 ==1:
leaves.append(leaves[-1:][0])# duplicate last
elem if odd number of elements
self.root: Node = self.__buildTreeRec(leaves)
def __buildTreeRec(self, nodes: List[Node])->
Node:
half: int = len(nodes) // 2
if len(nodes) == 2:
return Node(nodes[0], nodes[1],
Node.hash(nodes[0].value + nodes[1].value),
nodes[0].content+"+"+nodes[1].content)
left: Node = self.__buildTreeRec(nodes[:half])
right: Node = self.__buildTreeRec(nodes[half:])
value: str = Node.hash(left.value + right.value)
content: str =
self.__buildTreeRec(nodes[:half]).content+"+"+self.__buildTreeRec(nodes[half:]).content
return Node(left, right, value,content)
def printTree(self)-> None:
self.__printTreeRec(self.root)
def __printTreeRec(self, node)-> None:
if node != None:
if node.left != None:
print("Left: "+str(node.left))
print("Right: "+str(node.right))
else:
print("Input")
print("Value: "+str(node.value))
print("Content: "+str(node.content))
print("")
self.__printTreeRec(node.left)
self.__printTreeRec(node.right)
def getRootHash(self)-> str:
return self.root.value
#Finaly the test
def mixmerkletree()-> None:
elems = ["Mix", "Merkle", "Tree","From","Chucri
Simon Zouein","https://github.com/onuratakan/mixmerkletree","GO"]
print("Inputs: ")
print(*elems, sep = " | ")
print("")
mtree = MerkleTree(elems)
print("Root Hash: "+mtree.getRootHash()+"\n")
print(mtree.printTree())
mixmerkletree() |
| | |
- Output:
|
| | | |
|
|
3- |
Python Programs,
to display file type
= ("Text files", "*.txt") - NotePad + menu: New, Open, Save,
Save As, Exit |
|
|
|
|
- Python program, to
display file type = ("Text files",
"*.txt") - NotePad + menu: New, Open,
Save, Save As, Exit
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
PySFile
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
PySFile
- Projct
Folder: C:\Users\...\source\repos\PySFile
- Startup
File: PySFile.py
- Project
file: PySFile.sln
|
- Download Python
Project : PySFile.zip - (1.11
MB zip file) Download
- Project
consist of:
One Python Form -
(PySFile.py )
|
 | |
Download Python
Project : PySFile.zip - (1.11
MB zip file) Download
|
- Source Code:
Download this
Source Code at python file: PySFile.py
- (2.6 KB python file)
download
|
Download this
Source Code at txt file: PySFile.txt
- (2.6 KB txt file)
download
|
 |
Continue
|
Python Code,
to display file type = ("Text files",
"*.txt") - NotePad + menu: New, Open, Save, Save
As, Exit -
(python file :1.py)
| |
|
|
|
"""
work With file type = ("Text files", "*.txt") -
NotePad
New, Open, Save, Save As, Exit
"""
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
def file1():
if not text_zone.edit_modified():
text_zone.delete('1.0', tk.END)
else:
savefileas()
text_zone.delete('1.0', tk.END)
text_zone.edit_modified(0)
ws.title('PYTHON GUIDES')
def openfile():
if not text_zone.edit_modified():
try:
path = filedialog.askopenfile(filetypes =
(("Text files", "*.txt"), ("All files",
"*.*"))).name
ws.title('Notepad - ' + path)
with open(path, 'r') as f:
content = f.read()
text_zone.delete('1.0', tk.END)
text_zone.insert('1.0', content)
text_zone.edit_modified(0)
except:
pass
else:
savefileas()
text_zone.edit_modified(0)
openfile()
def savefile():
try:
path = ws.title().split('-')[1][1:]
except:
path = ''
if path != '':
with open(path, 'w') as f:
content = text_zone.get('1.0', tk.END)
f.write(content)
else:
savefileas()
text_zone.edit_modified(0)
def savefileas():
try:
path = filedialog.asksaveasfile(filetypes =
(("Text files", "*.txt"), ("All files",
"*.*"))).name
ws.title('Notepad - ' + path)
except:
return
with open(path, 'w') as f:
f.write(text_zone.get('1.0', tk.END))
ws = tk.Tk()
ws.title('Notepad')
ws.geometry('800x600')
menubar = tk.Menu(ws)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=file1)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_command(label="Save", command=savefile)
filemenu.add_command(label="Save as...",
command=savefileas)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=ws.quit)
menubar.add_cascade(label="File", menu=filemenu)
text_zone = tk.Text(ws)
text_zone.pack(expand = tk.YES, fill = tk.BOTH,
side = tk.LEFT)
scrollbar = ttk.Scrollbar(ws, orient=tk.VERTICAL,
command=text_zone.yview)
scrollbar.pack(fill=tk.Y, side=tk.RIGHT)
text_zone['yscrollcommand'] = scrollbar.set
ws.config(menu=menubar)
ws.mainloop() |
|
| | |
- Output:
|
Menu Function |
|
Open
Function |
|
Save As
Function |
| |
| | |
|
|
4- |
Python program,
to Display a Spreadsheet |
|
|
- Python program, to
Display a Spreadsheet
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
Pyspreadsh
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
Pyspreadsh
- Projct
Folder: C:\Users\...\source\repos\Pyspreadsh
- Startup
File: Pyspreadsh.py
- Project
file: Pyspreadsh.sln
|
- Download Python
Project : Pyspreadsh.zip -
(2.38 KB zip file) Download
- Project
consist of:
One Python Form -
(Pyspreadsh.py )
|
 | |
Download Python
Project : Pyspreadsh.zip -
(2.38 KB zip file) Download
|
- Source Code:
Download
this Source Code at python file
:Pyspreadsh.py - (2.58 KB Python
file) download
|
Download this
Source Code at txt file: Pyspreadsh.txt
- (2.58 KB txt file)
download
|
|
Continue
|
Python Code, to display a spreadsheet
- (python file :Pyspreadsh.py) | |
|
|
|
"""
SS1 -- a spreadsheet-like application.
"""
import os
import re
import sys
from xml.parsers import expat
from xml.sax.saxutils import escape
LEFT, CENTER, RIGHT = "LEFT", "CENTER", "RIGHT"
def ljust(x, n):
return x.ljust(n)
def center(x, n):
return x.center(n)
def rjust(x, n):
return x.rjust(n)
align2action = {LEFT: ljust, CENTER: center,
RIGHT: rjust}
align2xml = {LEFT: "left", CENTER: "center",
RIGHT: "right"}
xml2align = {"left": LEFT, "center": CENTER,
"right": RIGHT}
align2anchor = {LEFT: "w", CENTER: "center",
RIGHT: "e"}
def sum(seq):
total = 0
for x in seq:
if x is not None:
total += x
return total
class Sheet:
def __init__(self):
self.cells = {} # {(x, y): cell, ...}
self.ns = dict(
cell = self.cellvalue,
cells = self.multicellvalue,
sum = sum,
)
def cellvalue(self, x, y):
cell = self.getcell(x, y)
if hasattr(cell, 'recalc'):
return cell.recalc(self.ns)
else:
return cell
def multicellvalue(self, x1, y1, x2, y2):
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
seq = []
for y in range(y1, y2+1):
for x in range(x1, x2+1):
seq.append(self.cellvalue(x, y))
return seq
def getcell(self, x, y):
return self.cells.get((x, y))
def setcell(self, x, y, cell):
assert x > 0 and y > 0
assert isinstance(cell, BaseCell)
self.cells[x, y] = cell
def clearcell(self, x, y):
try:
del self.cells[x, y]
except KeyError:
pass
def clearcells(self, x1, y1, x2, y2):
for xy in self.selectcells(x1, y1, x2, y2):
del self.cells[xy]
def clearrows(self, y1, y2):
self.clearcells(0, y1, sys.maxsize, y2)
def clearcolumns(self, x1, x2):
self.clearcells(x1, 0, x2, sys.maxsize)
def selectcells(self, x1, y1, x2, y2):
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
return [(x, y) for x, y in self.cells
if x1 <= x <= x2 and y1 <= y <= y2]
def movecells(self, x1, y1, x2, y2, dx, dy):
if dx == 0 and dy == 0:
return
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
assert x1+dx > 0 and y1+dy > 0
new = {}
for x, y in self.cells:
cell = self.cells[x, y]
if hasattr(cell, 'renumber'):
cell = cell.renumber(x1, y1, x2, y2, dx, dy)
if x1 <= x <= x2 and y1 <= y <= y2:
x += dx
y += dy
new[x, y] = cell
self.cells = new
def insertrows(self, y, n):
assert n > 0
self.movecells(0, y, sys.maxsize, sys.maxsize,
0, n)
def deleterows(self, y1, y2):
if y1 > y2:
y1, y2 = y2, y1
self.clearrows(y1, y2)
self.movecells(0, y2+1, sys.maxsize, sys.maxsize,
0, y1-y2-1)
def insertcolumns(self, x, n):
assert n > 0
self.movecells(x, 0, sys.maxsize, sys.maxsize,
n, 0)
def deletecolumns(self, x1, x2):
if x1 > x2:
x1, x2 = x2, x1
self.clearcells(x1, x2)
self.movecells(x2+1, 0, sys.maxsize, sys.maxsize,
x1-x2-1, 0)
def getsize(self):
maxx = maxy = 0
for x, y in self.cells:
maxx = max(maxx, x)
maxy = max(maxy, y)
return maxx, maxy
def reset(self):
for cell in self.cells.values():
if hasattr(cell, 'reset'):
cell.reset()
def recalc(self):
self.reset()
for cell in self.cells.values():
if hasattr(cell, 'recalc'):
cell.recalc(self.ns)
def display(self):
maxx, maxy = self.getsize()
width, height = maxx+1, maxy+1
colwidth = [1] * width
full = {}
# Add column heading labels in row 0
for x in range(1, width):
full[x, 0] = text, alignment = colnum2name(x),
RIGHT
colwidth[x] = max(colwidth[x], len(text))
# Add row labels in column 0
for y in range(1, height):
full[0, y] = text, alignment = str(y), RIGHT
colwidth[0] = max(colwidth[0], len(text))
# Add sheet cells in columns with x>0 and y>0
for (x, y), cell in self.cells.items():
if x <= 0 or y <= 0:
continue
if hasattr(cell, 'recalc'):
cell.recalc(self.ns)
if hasattr(cell, 'format'):
text, alignment = cell.format()
assert isinstance(text, str)
assert alignment in (LEFT, CENTER, RIGHT)
else:
text = str(cell)
if isinstance(cell, str):
alignment = LEFT
else:
alignment = RIGHT
full[x, y] = (text, alignment)
colwidth[x] = max(colwidth[x], len(text))
# Calculate the horizontal separator line
(dashes and dots)
sep = ""
for x in range(width):
if sep:
sep += "+"
sep += "-"*colwidth[x]
# Now print The full grid
for y in range(height):
line = ""
for x in range(width):
text, alignment = full.get((x, y)) or ("", LEFT)
text = align2action[alignment](text, colwidth[x])
if line:
line += '|'
line += text
print(line)
if y == 0:
print(sep)
def xml(self):
out = ['<spreadsheet>']
for (x, y), cell in self.cells.items():
if hasattr(cell, 'xml'):
cellxml = cell.xml()
else:
cellxml = '<value>%s</value>' % escape(cell)
out.append('<cell row="%s" col="%s">\n
%s\n</cell>' %
(y, x, cellxml))
out.append('</spreadsheet>')
return '\n'.join(out)
def save(self, filename):
text = self.xml()
with open(filename, "w", encoding='utf-8') as f:
f.write(text)
if text and not text.endswith('\n'):
f.write('\n')
def load(self, filename):
with open(filename, 'rb') as f:
SheetParser(self).parsefile(f)
class SheetParser:
def __init__(self, sheet):
self.sheet = sheet
def parsefile(self, f):
parser = expat.ParserCreate()
parser.StartElementHandler = self.startelement
parser.EndElementHandler = self.endelement
parser.CharacterDataHandler = self.data
parser.ParseFile(f)
def startelement(self, tag, attrs):
method = getattr(self, 'start_'+tag, None)
if method:
method(attrs)
self.texts = []
def data(self, text):
self.texts.append(text)
def endelement(self, tag):
method = getattr(self, 'end_'+tag, None)
if method:
method("".join(self.texts))
def start_cell(self, attrs):
self.y = int(attrs.get("row"))
self.x = int(attrs.get("col"))
def start_value(self, attrs):
self.fmt = attrs.get('format')
self.alignment =
xml2align.get(attrs.get('align'))
start_formula = start_value
def end_int(self, text):
try:
self.value = int(text)
except (TypeError, ValueError):
self.value = None
end_long = end_int
def end_double(self, text):
try:
self.value = float(text)
except (TypeError, ValueError):
self.value = None
def end_complex(self, text):
try:
self.value = complex(text)
except (TypeError, ValueError):
self.value = None
def end_string(self, text):
self.value = text
def end_value(self, text):
if isinstance(self.value, BaseCell):
self.cell = self.value
elif isinstance(self.value, str):
self.cell = StringCell(self.value,
self.fmt or "%s",
self.alignment or LEFT)
else:
self.cell = NumericCell(self.value,
self.fmt or "%s",
self.alignment or RIGHT)
def end_formula(self, text):
self.cell = FormulaCell(text,
self.fmt or "%s",
self.alignment or RIGHT)
def end_cell(self, text):
self.sheet.setcell(self.x, self.y, self.cell)
class BaseCell:
__init__ = None # Must provide
"""Abstract base class for sheet cells.
Subclasses may but needn't provide the following
APIs:
cell.reset() -- prepare for recalculation
cell.recalc(ns) -> value -- recalculate formula
cell.format() -> (value, alignment) -- return
formatted value
cell.xml() -> string -- return XML
"""
class NumericCell(BaseCell):
def __init__(self, value, fmt="%s",
alignment=RIGHT):
assert isinstance(value, (int, float, complex))
assert alignment in (LEFT, CENTER, RIGHT)
self.value = value
self.fmt = fmt
self.alignment = alignment
def recalc(self, ns):
return self.value
def format(self):
try:
text = self.fmt % self.value
except:
text = str(self.value)
return text, self.alignment
def xml(self):
method = getattr(self, '_xml_' +
type(self.value).__name__)
return '<value align="%s"
format="%s">%s</value>' % (
align2xml[self.alignment],
self.fmt,
method())
def _xml_int(self):
if -2**31 <= self.value < 2**31:
return '<int>%s</int>' % self.value
else:
return '<long>%s</long>' % self.value
def _xml_float(self):
return '<double>%r</double>' % self.value
def _xml_complex(self):
return '<complex>%r</complex>' % self.value
class StringCell(BaseCell):
def __init__(self, text, fmt="%s",
alignment=LEFT):
assert isinstance(text, str)
assert alignment in (LEFT, CENTER, RIGHT)
self.text = text
self.fmt = fmt
self.alignment = alignment
def recalc(self, ns):
return self.text
def format(self):
return self.text, self.alignment
def xml(self):
s = '<value align="%s"
format="%s"><string>%s</string></value>'
return s % (
align2xml[self.alignment],
self.fmt,
escape(self.text))
class FormulaCell(BaseCell):
def __init__(self, formula, fmt="%s",
alignment=RIGHT):
assert alignment in (LEFT, CENTER, RIGHT)
self.formula = formula
self.translated = translate(self.formula)
self.fmt = fmt
self.alignment = alignment
self.reset()
def reset(self):
self.value = None
def recalc(self, ns):
if self.value is None:
try:
self.value = eval(self.translated, ns)
except:
exc = sys.exc_info()[0]
if hasattr(exc, "__name__"):
self.value = exc.__name__
else:
self.value = str(exc)
return self.value
def format(self):
try:
text = self.fmt % self.value
except:
text = str(self.value)
return text, self.alignment
def xml(self):
return '<formula align="%s"
format="%s">%s</formula>' % (
align2xml[self.alignment],
self.fmt,
escape(self.formula))
def renumber(self, x1, y1, x2, y2, dx, dy):
out = []
for part in re.split(r'(\w+)', self.formula):
m = re.match('^([A-Z]+)([1-9][0-9]*)$', part)
if m is not None:
sx, sy = m.groups()
x = colname2num(sx)
y = int(sy)
if x1 <= x <= x2 and y1 <= y <= y2:
part = cellname(x+dx, y+dy)
out.append(part)
return FormulaCell("".join(out), self.fmt,
self.alignment)
def translate(formula):
"""Translate a formula containing fancy cell
names to valid Python code.
Examples:
B4 -> cell(2, 4)
B4:Z100 -> cells(2, 4, 26, 100)
"""
out = []
for part in re.split(r"(\w+(?::\w+)?)",
formula):
m = re.match(r"^([A-Z]+)([1-9][0-9]*)(?::([A-Z]+)([1-9][0-9]*))?$",
part)
if m is None:
out.append(part)
else:
x1, y1, x2, y2 = m.groups()
x1 = colname2num(x1)
if x2 is None:
s = "cell(%s, %s)" % (x1, y1)
else:
x2 = colname2num(x2)
s = "cells(%s, %s, %s, %s)" % (x1, y1, x2, y2)
out.append(s)
return "".join(out)
def cellname(x, y):
"Translate a cell coordinate to a fancy cell
name (e.g. (1, 1)->'A1')."
assert x > 0 # Column 0 has an empty name, so
can't use that
return colnum2name(x) + str(y)
def colname2num(s):
"Translate a column name to number (e.g. 'A'->1,
'Z'->26, 'AA'->27)."
s = s.upper()
n = 0
for c in s:
assert 'A' <= c <= 'Z'
n = n*26 + ord(c) - ord('A') + 1
return n
def colnum2name(n):
"Translate a column number to name (e.g. 1->'A',
etc.)."
assert n > 0
s = ""
while n:
n, m = divmod(n-1, 26)
s = chr(m+ord('A')) + s
return s
import tkinter as Tk
class SheetGUI:
"""Beginnings of a GUI for a spreadsheet.
TO DO:
- clear multiple cells
- Insert, clear, remove rows or columns
- Show new contents while typing
- Scroll bars
- Grow grid when window is grown
- Proper menus
- Undo, redo
- Cut, copy and paste
- Formatting and alignment
"""
def __init__(self, filename="sheet1.xml",
rows=10, columns=5):
"""Constructor.
Load the sheet from the filename argument.
Set up the Tk widget tree.
"""
# Create and load the sheet
self.filename = filename
self.sheet = Sheet()
if os.path.isfile(filename):
self.sheet.load(filename)
# Calculate the needed grid size
maxx, maxy = self.sheet.getsize()
rows = max(rows, maxy)
columns = max(columns, maxx)
# Create the widgets
self.root = Tk.Tk()
self.root.wm_title("Spreadsheet: %s" %
self.filename)
self.beacon = Tk.Label(self.root, text="A1",
font=('helvetica', 16, 'bold'))
self.entry = Tk.Entry(self.root)
self.savebutton = Tk.Button(self.root,
text="Save",
command=self.save)
self.cellgrid = Tk.Frame(self.root)
# Configure the widget lay-out
self.cellgrid.pack(side="bottom", expand=1,
fill="both")
self.beacon.pack(side="left")
self.savebutton.pack(side="right")
self.entry.pack(side="left", expand=1, fill="x")
# Bind some events
self.entry.bind("<Return>", self.return_event)
self.entry.bind("<Shift-Return>",
self.shift_return_event)
self.entry.bind("<Tab>", self.tab_event)
self.entry.bind("<Shift-Tab>",
self.shift_tab_event)
self.entry.bind("<Delete>", self.delete_event)
self.entry.bind("<Escape>", self.escape_event)
# Now create the cell grid
self.makegrid(rows, columns)
# Select the top-left cell
self.currentxy = None
self.cornerxy = None
self.setcurrent(1, 1)
# Copy the sheet cells to the GUI cells
self.sync()
def delete_event(self, event):
if self.cornerxy != self.currentxy and
self.cornerxy is not None:
self.sheet.clearcells(*(self.currentxy +
self.cornerxy))
else:
self.sheet.clearcell(*self.currentxy)
self.sync()
self.entry.delete(0, 'end')
return "break"
def escape_event(self, event):
x, y = self.currentxy
self.load_entry(x, y)
def load_entry(self, x, y):
cell = self.sheet.getcell(x, y)
if cell is None:
text = ""
elif isinstance(cell, FormulaCell):
text = '=' + cell.formula
else:
text, alignment = cell.format()
self.entry.delete(0, 'end')
self.entry.insert(0, text)
self.entry.selection_range(0, 'end')
def makegrid(self, rows, columns):
"""Helper to create the grid of GUI cells.
The edge (x==0 or y==0) is filled with labels;
the rest is real cells.
"""
self.rows = rows
self.columns = columns
self.gridcells = {}
# Create the top left corner cell (which selects
all)
cell = Tk.Label(self.cellgrid, relief='raised')
cell.grid_configure(column=0, row=0, sticky='NSWE')
cell.bind("<ButtonPress-1>", self.selectall)
# Create the top row of labels, and configure
the grid columns
for x in range(1, columns+1):
self.cellgrid.grid_columnconfigure(x, minsize=64)
cell = Tk.Label(self.cellgrid,
text=colnum2name(x), relief='raised')
cell.grid_configure(column=x, row=0,
sticky='WE')
self.gridcells[x, 0] = cell
cell.__x = x
cell.__y = 0
cell.bind("<ButtonPress-1>", self.selectcolumn)
cell.bind("<B1-Motion>", self.extendcolumn)
cell.bind("<ButtonRelease-1>", self.extendcolumn)
cell.bind("<Shift-Button-1>", self.extendcolumn)
# Create the leftmost column of labels
for y in range(1, rows+1):
cell = Tk.Label(self.cellgrid, text=str(y),
relief='raised')
cell.grid_configure(column=0, row=y,
sticky='WE')
self.gridcells[0, y] = cell
cell.__x = 0
cell.__y = y
cell.bind("<ButtonPress-1>", self.selectrow)
cell.bind("<B1-Motion>", self.extendrow)
cell.bind("<ButtonRelease-1>", self.extendrow)
cell.bind("<Shift-Button-1>", self.extendrow)
# Create the real cells
for x in range(1, columns+1):
for y in range(1, rows+1):
cell = Tk.Label(self.cellgrid, relief='sunken',
bg='white', fg='black')
cell.grid_configure(column=x, row=y, sticky='NSWE')
self.gridcells[x, y] = cell
cell.__x = x
cell.__y = y
# Bind mouse events
cell.bind("<ButtonPress-1>", self.press)
cell.bind("<B1-Motion>", self.motion)
cell.bind("<ButtonRelease-1>", self.release)
cell.bind("<Shift-Button-1>", self.release)
def selectall(self, event):
self.setcurrent(1, 1)
self.setcorner(sys.maxsize, sys.maxsize)
def selectcolumn(self, event):
x, y = self.whichxy(event)
self.setcurrent(x, 1)
self.setcorner(x, sys.maxsize)
def extendcolumn(self, event):
x, y = self.whichxy(event)
if x > 0:
self.setcurrent(self.currentxy[0], 1)
self.setcorner(x, sys.maxsize)
def selectrow(self, event):
x, y = self.whichxy(event)
self.setcurrent(1, y)
self.setcorner(sys.maxsize, y)
def extendrow(self, event):
x, y = self.whichxy(event)
if y > 0:
self.setcurrent(1, self.currentxy[1])
self.setcorner(sys.maxsize, y)
def press(self, event):
x, y = self.whichxy(event)
if x > 0 and y > 0:
self.setcurrent(x, y)
def motion(self, event):
x, y = self.whichxy(event)
if x > 0 and y > 0:
self.setcorner(x, y)
release = motion
def whichxy(self, event):
w = self.cellgrid.winfo_containing(event.x_root,
event.y_root)
if w is not None and isinstance(w, Tk.Label):
try:
return w.__x, w.__y
except AttributeError:
pass
return 0, 0
def save(self):
self.sheet.save(self.filename)
def setcurrent(self, x, y):
"Make (x, y) the current cell."
if self.currentxy is not None:
self.change_cell()
self.clearfocus()
self.beacon['text'] = cellname(x, y)
self.load_entry(x, y)
self.entry.focus_set()
self.currentxy = x, y
self.cornerxy = None
gridcell = self.gridcells.get(self.currentxy)
if gridcell is not None:
gridcell['bg'] = 'yellow'
def setcorner(self, x, y):
if self.currentxy is None or self.currentxy ==
(x, y):
self.setcurrent(x, y)
return
self.clearfocus()
self.cornerxy = x, y
x1, y1 = self.currentxy
x2, y2 = self.cornerxy or self.currentxy
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
for (x, y), cell in self.gridcells.items():
if x1 <= x <= x2 and y1 <= y <= y2:
cell['bg'] = 'lightBlue'
gridcell = self.gridcells.get(self.currentxy)
if gridcell is not None:
gridcell['bg'] = 'yellow'
self.setbeacon(x1, y1, x2, y2)
def setbeacon(self, x1, y1, x2, y2):
if x1 == y1 == 1 and x2 == y2 == sys.maxsize:
name = ":"
elif (x1, x2) == (1, sys.maxsize):
if y1 == y2:
name = "%d" % y1
else:
name = "%d:%d" % (y1, y2)
elif (y1, y2) == (1, sys.maxsize):
if x1 == x2:
name = "%s" % colnum2name(x1)
else:
name = "%s:%s" % (colnum2name(x1),
colnum2name(x2))
else:
name1 = cellname(*self.currentxy)
name2 = cellname(*self.cornerxy)
name = "%s:%s" % (name1, name2)
self.beacon['text'] = name
def clearfocus(self):
if self.currentxy is not None:
x1, y1 = self.currentxy
x2, y2 = self.cornerxy or self.currentxy
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
for (x, y), cell in self.gridcells.items():
if x1 <= x <= x2 and y1 <= y <= y2:
cell['bg'] = 'white'
def return_event(self, event):
"Callback for the Return key."
self.change_cell()
x, y = self.currentxy
self.setcurrent(x, y+1)
return "break"
def shift_return_event(self, event):
"Callback for the Return key with Shift
modifier."
self.change_cell()
x, y = self.currentxy
self.setcurrent(x, max(1, y-1))
return "break"
def tab_event(self, event):
"Callback for the Tab key."
self.change_cell()
x, y = self.currentxy
self.setcurrent(x+1, y)
return "break"
def shift_tab_event(self, event):
"Callback for the Tab key with Shift modifier."
self.change_cell()
x, y = self.currentxy
self.setcurrent(max(1, x-1), y)
return "break"
def change_cell(self):
"Set the current cell from the entry widget."
x, y = self.currentxy
text = self.entry.get()
cell = None
if text.startswith('='):
cell = FormulaCell(text[1:])
else:
for cls in int, float, complex:
try:
value = cls(text)
except (TypeError, ValueError):
continue
else:
cell = NumericCell(value)
break
if cell is None and text:
cell = StringCell(text)
if cell is None:
self.sheet.clearcell(x, y)
else:
self.sheet.setcell(x, y, cell)
self.sync()
def sync(self):
"Fill the GUI cells from the sheet cells."
self.sheet.recalc()
for (x, y), gridcell in self.gridcells.items():
if x == 0 or y == 0:
continue
cell = self.sheet.getcell(x, y)
if cell is None:
gridcell['text'] = ""
else:
if hasattr(cell, 'format'):
text, alignment = cell.format()
else:
text, alignment = str(cell), LEFT
gridcell['text'] = text
gridcell['anchor'] = align2anchor[alignment]
def test_basic():
"Basic non-gui self-test."
a = Sheet()
for x in range(1, 11):
for y in range(1, 11):
if x == 1:
cell = NumericCell(y)
elif y == 1:
cell = NumericCell(x)
else:
c1 = cellname(x, 1)
c2 = cellname(1, y)
formula = "%s*%s" % (c1, c2)
cell = FormulaCell(formula)
a.setcell(x, y, cell)
## if os.path.isfile("sheet1.xml"):
## print "Loading from sheet1.xml"
## a.load("sheet1.xml")
a.display()
a.save("sheet1.xml")
def test_gui():
"GUI test."
if sys.argv[1:]:
filename = sys.argv[1]
else:
filename = "sheet1.xml"
g = SheetGUI(filename)
g.root.mainloop()
if __name__ == '__main__':
#test_basic()
test_gui()
|
|
| | |
- Output :
 |
a spreadsheet
| |
| | | |
|
|
5- |
Python
program, Sorting algorithms visualizer using Tkinter |
|
|
|
|
- Python program, Sorting
algorithms visualizer using Tkinter
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
py-sortv
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
py-sortv
- Projct
Folder: C:\Users\...\source\repos\py-sortv
- Startup
File: py_sortv.py
- Project
file: py-sortv.sln
|
- Download Python
Project : py_sortv.zip -
(18.4KB zip file)
Download
- Project
consist of:
One Python Form -
(py_sortv.py )
|
 | |
Download Python
Project : py-sortv.zip -
(18.4 KB zip file) Download
|
- Source Code:
-
Download this Source Code at
python file: py_sortv.py
- (20.1 KB Python
file)
download
|
Download this
Source Code at txt file: py-sortv.txt
- (20.12 KB txt file)
download
|
 |
Continue |
Python Code,
to display Sorting algorithms visualizer
using Tkinter -
(python file :1.py) | |
|
|
|
"""
Sorting algorithms visualizer using Tkinter.
This module is comprised of three
``components'':
- an array visualizer with methods that
implement basic sorting
operations (compare, swap) as well as methods
for ``annotating'' the
sorting algorithm (e.g. to show the pivot
element);
- a number of sorting algorithms (currently
quicksort, insertion sort,
selection sort and bubble sort, as well as a
randomization function),
all using the array visualizer for its basic
operations and with calls
to its annotation methods;
- and a ``driver'' class which can be used as a
Grail applet or as a
stand-alone application.
"""
from tkinter import *
import random
XGRID = 10
YGRID = 10
WIDTH = 6
class Array:
class Cancelled(BaseException):
pass
def __init__(self, master, data=None):
self.master = master
self.frame = Frame(self.master)
self.frame.pack(fill=X)
self.label = Label(self.frame)
self.label.pack()
self.canvas = Canvas(self.frame)
self.canvas.pack()
self.report = Label(self.frame)
self.report.pack()
self.left = self.canvas.create_line(0, 0, 0, 0)
self.right = self.canvas.create_line(0, 0, 0, 0)
self.pivot = self.canvas.create_line(0, 0, 0, 0)
self.items = []
self.size = self.maxvalue = 0
if data:
self.setdata(data)
def setdata(self, data):
olditems = self.items
self.items = []
for item in olditems:
item.delete()
self.size = len(data)
self.maxvalue = max(data)
self.canvas.config(width=(self.size+1)*XGRID,
height=(self.maxvalue+1)*YGRID)
for i in range(self.size):
self.items.append(ArrayItem(self, i, data[i]))
self.reset("Sort demo, size %d" % self.size)
speed = "normal"
def setspeed(self, speed):
self.speed = speed
def destroy(self):
self.frame.destroy()
in_mainloop = 0
stop_mainloop = 0
def cancel(self):
self.stop_mainloop = 1
if self.in_mainloop:
self.master.quit()
def step(self):
if self.in_mainloop:
self.master.quit()
def wait(self, msecs):
if self.speed == "fastest":
msecs = 0
elif self.speed == "fast":
msecs = msecs//10
elif self.speed == "single-step":
msecs = 1000000000
if not self.stop_mainloop:
self.master.update()
id = self.master.after(msecs, self.master.quit)
self.in_mainloop = 1
self.master.mainloop()
self.master.after_cancel(id)
self.in_mainloop = 0
if self.stop_mainloop:
self.stop_mainloop = 0
self.message("Cancelled")
raise Array.Cancelled
def getsize(self):
return self.size
def show_partition(self, first, last):
for i in range(self.size):
item = self.items[i]
if first <= i < last:
self.canvas.itemconfig(item, fill='red')
else:
self.canvas.itemconfig(item, fill='orange')
self.hide_left_right_pivot()
def hide_partition(self):
for i in range(self.size):
item = self.items[i]
self.canvas.itemconfig(item, fill='red')
self.hide_left_right_pivot()
def show_left(self, left):
if not 0 <= left < self.size:
self.hide_left()
return
x1, y1, x2, y2 = self.items[left].position()
## top, bot = HIRO
self.canvas.coords(self.left, (x1 - 2, 0, x1 -
2, 9999))
self.master.update()
def show_right(self, right):
if not 0 <= right < self.size:
self.hide_right()
return
x1, y1, x2, y2 = self.items[right].position()
self.canvas.coords(self.right, (x2 + 2, 0, x2 +
2, 9999))
self.master.update()
def hide_left_right_pivot(self):
self.hide_left()
self.hide_right()
self.hide_pivot()
def hide_left(self):
self.canvas.coords(self.left, (0, 0, 0, 0))
def hide_right(self):
self.canvas.coords(self.right, (0, 0, 0, 0))
def show_pivot(self, pivot):
x1, y1, x2, y2 = self.items[pivot].position()
self.canvas.coords(self.pivot, (0, y1 - 2, 9999,
y1 - 2))
def hide_pivot(self):
self.canvas.coords(self.pivot, (0, 0, 0, 0))
def swap(self, i, j):
if i == j: return
self.countswap()
item = self.items[i]
other = self.items[j]
self.items[i], self.items[j] = other, item
item.swapwith(other)
def compare(self, i, j):
self.countcompare()
item = self.items[i]
other = self.items[j]
return item.compareto(other)
def reset(self, msg):
self.ncompares = 0
self.nswaps = 0
self.message(msg)
self.updatereport()
self.hide_partition()
def message(self, msg):
self.label.config(text=msg)
def countswap(self):
self.nswaps = self.nswaps + 1
self.updatereport()
def countcompare(self):
self.ncompares = self.ncompares + 1
self.updatereport()
def updatereport(self):
text = "%d cmps, %d swaps" % (self.ncompares,
self.nswaps)
self.report.config(text=text)
class ArrayItem:
def __init__(self, array, index, value):
self.array = array
self.index = index
self.value = value
self.canvas = array.canvas
x1, y1, x2, y2 = self.position()
self.item_id = array.canvas.create_rectangle(x1,
y1, x2, y2,
fill='red', outline='black', width=1)
self.canvas.tag_bind(self.item_id, '<Button-1>',
self.mouse_down)
self.canvas.tag_bind(self.item_id,
'<Button1-Motion>', self.mouse_move)
self.canvas.tag_bind(self.item_id,
'<ButtonRelease-1>', self.mouse_up)
def delete(self):
item_id = self.item_id
self.array = None
self.item_id = None
self.canvas.delete(item_id)
def mouse_down(self, event):
self.lastx = event.x
self.lasty = event.y
self.origx = event.x
self.origy = event.y
self.canvas.tag_raise(self.item_id)
def mouse_move(self, event):
self.canvas.move(self.item_id,
event.x - self.lastx, event.y - self.lasty)
self.lastx = event.x
self.lasty = event.y
def mouse_up(self, event):
i = self.nearestindex(event.x)
if i >= self.array.getsize():
i = self.array.getsize() - 1
if i < 0:
i = 0
other = self.array.items[i]
here = self.index
self.array.items[here], self.array.items[i] =
other, self
self.index = i
x1, y1, x2, y2 = self.position()
self.canvas.coords(self.item_id, (x1, y1, x2,
y2))
other.setindex(here)
def setindex(self, index):
nsteps = steps(self.index, index)
if not nsteps: return
if self.array.speed == "fastest":
nsteps = 0
oldpts = self.position()
self.index = index
newpts = self.position()
trajectory = interpolate(oldpts, newpts, nsteps)
self.canvas.tag_raise(self.item_id)
for pts in trajectory:
self.canvas.coords(self.item_id, pts)
self.array.wait(50)
def swapwith(self, other):
nsteps = steps(self.index, other.index)
if not nsteps: return
if self.array.speed == "fastest":
nsteps = 0
myoldpts = self.position()
otheroldpts = other.position()
self.index, other.index = other.index,
self.index
mynewpts = self.position()
othernewpts = other.position()
myfill = self.canvas.itemcget(self.item_id,
'fill')
otherfill = self.canvas.itemcget(other.item_id,
'fill')
self.canvas.itemconfig(self.item_id,
fill='green')
self.canvas.itemconfig(other.item_id,
fill='yellow')
self.array.master.update()
if self.array.speed == "single-step":
self.canvas.coords(self.item_id, mynewpts)
self.canvas.coords(other.item_id, othernewpts)
self.array.master.update()
self.canvas.itemconfig(self.item_id, fill=myfill)
self.canvas.itemconfig(other.item_id, fill=otherfill)
self.array.wait(0)
return
mytrajectory = interpolate(myoldpts, mynewpts,
nsteps)
othertrajectory = interpolate(otheroldpts,
othernewpts, nsteps)
if self.value > other.value:
self.canvas.tag_raise(self.item_id)
self.canvas.tag_raise(other.item_id)
else:
self.canvas.tag_raise(other.item_id)
self.canvas.tag_raise(self.item_id)
try:
for i in range(len(mytrajectory)):
mypts = mytrajectory[i]
otherpts = othertrajectory[i]
self.canvas.coords(self.item_id, mypts)
self.canvas.coords(other.item_id, otherpts)
self.array.wait(50)
finally:
mypts = mytrajectory[-1]
otherpts = othertrajectory[-1]
self.canvas.coords(self.item_id, mypts)
self.canvas.coords(other.item_id, otherpts)
self.canvas.itemconfig(self.item_id, fill=myfill)
self.canvas.itemconfig(other.item_id, fill=otherfill)
def compareto(self, other):
myfill = self.canvas.itemcget(self.item_id,
'fill')
otherfill = self.canvas.itemcget(other.item_id,
'fill')
if self.value < other.value:
myflash = 'white'
otherflash = 'black'
outcome = -1
elif self.value > other.value:
myflash = 'black'
otherflash = 'white'
outcome = 1
else:
myflash = otherflash = 'grey'
outcome = 0
try:
self.canvas.itemconfig(self.item_id, fill=myflash)
self.canvas.itemconfig(other.item_id, fill=otherflash)
self.array.wait(500)
finally:
self.canvas.itemconfig(self.item_id, fill=myfill)
self.canvas.itemconfig(other.item_id, fill=otherfill)
return outcome
def position(self):
x1 = (self.index+1)*XGRID - WIDTH//2
x2 = x1+WIDTH
y2 = (self.array.maxvalue+1)*YGRID
y1 = y2 - (self.value)*YGRID
return x1, y1, x2, y2
def nearestindex(self, x):
return int(round(float(x)/XGRID)) - 1
# Subroutines that don't need an object
def steps(here, there):
nsteps = abs(here - there)
if nsteps <= 3:
nsteps = nsteps * 3
elif nsteps <= 5:
nsteps = nsteps * 2
elif nsteps > 10:
nsteps = 10
return nsteps
def interpolate(oldpts, newpts, n):
if len(oldpts) != len(newpts):
raise ValueError("can't interpolate arrays of
different length")
pts = [0]*len(oldpts)
res = [tuple(oldpts)]
for i in range(1, n):
for k in range(len(pts)):
pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i//n
res.append(tuple(pts))
res.append(tuple(newpts))
return res
# Various (un)sorting algorithms
def uniform(array):
size = array.getsize()
array.setdata([(size+1)//2] * size)
array.reset("Uniform data, size %d" % size)
def distinct(array):
size = array.getsize()
array.setdata(range(1, size+1))
array.reset("Distinct data, size %d" % size)
def randomize(array):
array.reset("Randomizing")
n = array.getsize()
for i in range(n):
j = random.randint(0, n-1)
array.swap(i, j)
array.message("Randomized")
def insertionsort(array):
size = array.getsize()
array.reset("Insertion sort")
for i in range(1, size):
j = i-1
while j >= 0:
if array.compare(j, j+1) <= 0:
break
array.swap(j, j+1)
j = j-1
array.message("Sorted")
def selectionsort(array):
size = array.getsize()
array.reset("Selection sort")
try:
for i in range(size):
array.show_partition(i, size)
for j in range(i+1, size):
if array.compare(i, j) > 0:
array.swap(i, j)
array.message("Sorted")
finally:
array.hide_partition()
def bubblesort(array):
size = array.getsize()
array.reset("Bubble sort")
for i in range(size):
for j in range(1, size):
if array.compare(j-1, j) > 0:
array.swap(j-1, j)
array.message("Sorted")
def quicksort(array):
size = array.getsize()
array.reset("Quicksort")
try:
stack = [(0, size)]
while stack:
first, last = stack[-1]
del stack[-1]
array.show_partition(first, last)
if last-first < 5:
array.message("Insertion sort")
for i in range(first+1, last):
j = i-1
while j >= first:
if array.compare(j, j+1) <= 0:
break
array.swap(j, j+1)
j = j-1
continue
array.message("Choosing pivot")
j, i, k = first, (first+last) // 2, last-1
if array.compare(k, i) < 0:
array.swap(k, i)
if array.compare(k, j) < 0:
array.swap(k, j)
if array.compare(j, i) < 0:
array.swap(j, i)
pivot = j
array.show_pivot(pivot)
array.message("Pivot at left of partition")
array.wait(1000)
left = first
right = last
while True:
array.message("Sweep right pointer")
right = right-1
array.show_right(right)
while right > first and array.compare(right,
pivot) >= 0:
right = right-1
array.show_right(right)
array.message("Sweep left pointer")
left = left+1
array.show_left(left)
while left < last and array.compare(left, pivot)
<= 0:
left = left+1
array.show_left(left)
if left > right:
array.message("End of partition")
break
array.message("Swap items")
array.swap(left, right)
array.message("Swap pivot back")
array.swap(pivot, right)
n1 = right-first
n2 = last-left
if n1 > 1: stack.append((first, right))
if n2 > 1: stack.append((left, last))
array.message("Sorted")
finally:
array.hide_partition()
def demosort(array):
while True:
for alg in [quicksort, insertionsort,
selectionsort, bubblesort]:
randomize(array)
alg(array)
# Sort demo class -- usable as a Grail applet
class SortDemo:
def __init__(self, master, size=15):
self.master = master
self.size = size
self.busy = 0
self.array = Array(self.master)
self.botframe = Frame(master)
self.botframe.pack(side=BOTTOM)
self.botleftframe = Frame(self.botframe)
self.botleftframe.pack(side=LEFT, fill=Y)
self.botrightframe = Frame(self.botframe)
self.botrightframe.pack(side=RIGHT, fill=Y)
self.b_qsort = Button(self.botleftframe,
text="Quicksort", command=self.c_qsort)
self.b_qsort.pack(fill=X)
self.b_isort = Button(self.botleftframe,
text="Insertion sort", command=self.c_isort)
self.b_isort.pack(fill=X)
self.b_ssort = Button(self.botleftframe,
text="Selection sort", command=self.c_ssort)
self.b_ssort.pack(fill=X)
self.b_bsort = Button(self.botleftframe,
text="Bubble sort", command=self.c_bsort)
self.b_bsort.pack(fill=X)
# Terrible hack to overcome limitation of
OptionMenu...
class MyIntVar(IntVar):
def __init__(self, master, demo):
self.demo = demo
IntVar.__init__(self, master)
def set(self, value):
IntVar.set(self, value)
if str(value) != '0':
self.demo.resize(value)
self.v_size = MyIntVar(self.master, self)
self.v_size.set(size)
sizes = [1, 2, 3, 4] + list(range(5, 55, 5))
if self.size not in sizes:
sizes.append(self.size)
sizes.sort()
self.m_size = OptionMenu(self.botleftframe,
self.v_size, *sizes)
self.m_size.pack(fill=X)
self.v_speed = StringVar(self.master)
self.v_speed.set("normal")
self.m_speed = OptionMenu(self.botleftframe,
self.v_speed,
"single-step", "normal", "fast", "fastest")
self.m_speed.pack(fill=X)
self.b_step = Button(self.botleftframe,
text="Step", command=self.c_step)
self.b_step.pack(fill=X)
self.b_randomize = Button(self.botrightframe,
text="Randomize", command=self.c_randomize)
self.b_randomize.pack(fill=X)
self.b_uniform = Button(self.botrightframe,
text="Uniform", command=self.c_uniform)
self.b_uniform.pack(fill=X)
self.b_distinct = Button(self.botrightframe,
text="Distinct", command=self.c_distinct)
self.b_distinct.pack(fill=X)
self.b_demo = Button(self.botrightframe,
text="Demo", command=self.c_demo)
self.b_demo.pack(fill=X)
self.b_cancel = Button(self.botrightframe,
text="Cancel", command=self.c_cancel)
self.b_cancel.pack(fill=X)
self.b_cancel.config(state=DISABLED)
self.b_quit = Button(self.botrightframe,
text="Quit", command=self.c_quit)
self.b_quit.pack(fill=X)
def resize(self, newsize):
if self.busy:
self.master.bell()
return
self.size = newsize
self.array.setdata(range(1, self.size+1))
def c_qsort(self):
self.run(quicksort)
def c_isort(self):
self.run(insertionsort)
def c_ssort(self):
self.run(selectionsort)
def c_bsort(self):
self.run(bubblesort)
def c_demo(self):
self.run(demosort)
def c_randomize(self):
self.run(randomize)
def c_uniform(self):
self.run(uniform)
def c_distinct(self):
self.run(distinct)
def run(self, func):
if self.busy:
self.master.bell()
return
self.busy = 1
self.array.setspeed(self.v_speed.get())
self.b_cancel.config(state=NORMAL)
try:
func(self.array)
except Array.Cancelled:
pass
self.b_cancel.config(state=DISABLED)
self.busy = 0
def c_cancel(self):
if not self.busy:
self.master.bell()
return
self.array.cancel()
def c_step(self):
if not self.busy:
self.master.bell()
return
self.v_speed.set("single-step")
self.array.setspeed("single-step")
self.array.step()
def c_quit(self):
if self.busy:
self.array.cancel()
self.master.after_idle(self.master.quit)
# Main program -- for stand-alone operation
outside Grail
def main():
root = Tk()
demo = SortDemo(root)
root.protocol('WM_DELETE_WINDOW', demo.c_quit)
root.mainloop()
if __name__ == '__main__':
main() |
|
|
| | |
- Output:
Pic default, 1, 2 and 3 |
|
Pic
4 and 5 | |
| | | |
|
|
6- |
Python
program, Python Game - 1 |
|
|
|
- Python program, Python
Game - 1
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
PyGamePuz
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
PyGamePuz
- Projct
Folder: C:\Users\...\source\repos\PyGamePuz
- Startup
File: PyGamePuz.py
- Project
file: PyGamePuz.sln
|
- Download Python
Project : PyGamePuz.zip -
(15.5 KB zip file)
Download
- Project
consist of:
One Python Form -
(PyGamePuz.py )
|
 | |
Download Python
Project : PyGamePuz.zip -
(15.5 KB zip file) Download
|
- Source Code:
- ource Code:
|
|
Download this
Source Code at python file: PyGamePuz.py
- (12.1 KB Python
file)
download
|
|
|
Download this
Source Code at txt file: PyGamePuz.txt
- (12.1 KB txt file)
download
| |
 |
Continue
|
Python Code
file, to display Python Game
- (python file :PyGamePuz.py) | |
|
|
|
"""
Python Game
"""
import pygame
import sys
import random
from pygame.locals import *
# Create the constants (go ahead and experiment
with different values)
BOARDWIDTH = 4 # number of columns in the board
BOARDHEIGHT = 4 # number of rows in the board
TILESIZE = 80
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
FPS = 30
BLANK = None
# R G B
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BRIGHTBLUE = ( 0, 50, 255)
DARKTURQUOISE = ( 3, 54, 73)
GREEN = ( 0, 204, 0)
BGCOLOR = DARKTURQUOISE
TILECOLOR = GREEN
TEXTCOLOR = WHITE
BORDERCOLOR = BRIGHTBLUE
BASICFONTSIZE = 20
BUTTONCOLOR = WHITE
BUTTONTEXTCOLOR = BLACK
MESSAGECOLOR = WHITE
XMARGIN = int((WINDOWWIDTH - (TILESIZE *
BOARDWIDTH + (BOARDWIDTH - 1))) / 2)
YMARGIN = int((WINDOWHEIGHT - (TILESIZE *
BOARDHEIGHT + (BOARDHEIGHT - 1))) / 2)
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT,
RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT,
SOLVE_SURF, SOLVE_RECT
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF =
pygame.display.set_mode((WINDOWWIDTH,
WINDOWHEIGHT))
pygame.display.set_caption('Slide Puzzle')
BASICFONT = pygame.font.Font('freesansbold.ttf',
BASICFONTSIZE)
# Store the option buttons and their rectangles
in OPTIONS.
RESET_SURF, RESET_RECT = makeText('Reset',
TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120,
WINDOWHEIGHT - 90)
NEW_SURF, NEW_RECT = makeText('New Game',
TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120,
WINDOWHEIGHT - 60)
SOLVE_SURF, SOLVE_RECT = makeText('Solve',
TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120,
WINDOWHEIGHT - 30)
mainBoard, solutionSeq = generateNewPuzzle(80)
SOLVEDBOARD = getStartingBoard() # a solved
board is the same as the board in a start state.
allMoves = [] # list of moves made from the
solved configuration
while True: # main game loop
slideTo = None # the direction, if any, a tile
should slide
msg = 'Click tile or press arrow keys to slide.'
# contains the message to show in the upper left
corner.
if mainBoard == SOLVEDBOARD:
msg = 'Solved!'
drawBoard(mainBoard, msg)
checkForQuit()
for event in pygame.event.get(): # event
handling loop
if event.type == MOUSEBUTTONUP:
spotx, spoty = getSpotClicked(mainBoard,
event.pos[0], event.pos[1])
if (spotx, spoty) == (None, None):
# check if the user clicked on an option button
if RESET_RECT.collidepoint(event.pos):
resetAnimation(mainBoard, allMoves) # clicked on
Reset button
allMoves = []
elif NEW_RECT.collidepoint(event.pos):
mainBoard, solutionSeq = generateNewPuzzle(80) #
clicked on New Game button
allMoves = []
elif SOLVE_RECT.collidepoint(event.pos):
resetAnimation(mainBoard, solutionSeq + allMoves)
# clicked on Solve button
allMoves = []
else:
# check if the clicked tile was next to the
blank spot
blankx, blanky = getBlankPosition(mainBoard)
if spotx == blankx + 1 and spoty == blanky:
slideTo = LEFT
elif spotx == blankx - 1 and spoty == blanky:
slideTo = RIGHT
elif spotx == blankx and spoty == blanky + 1:
slideTo = UP
elif spotx == blankx and spoty == blanky - 1:
slideTo = DOWN
elif event.type == KEYUP:
# check if the user pressed a key to slide a
tile
if event.key in (K_LEFT, K_a) and
isValidMove(mainBoard, LEFT):
slideTo = LEFT
elif event.key in (K_RIGHT, K_d) and
isValidMove(mainBoard, RIGHT):
slideTo = RIGHT
elif event.key in (K_UP, K_w) and
isValidMove(mainBoard, UP):
slideTo = UP
elif event.key in (K_DOWN, K_s) and
isValidMove(mainBoard, DOWN):
slideTo = DOWN
if slideTo:
slideAnimation(mainBoard, slideTo, 'Click tile
or press arrow keys to slide.', 8) # show slide
on screen
makeMove(mainBoard, slideTo)
allMoves.append(slideTo) # record the slide
pygame.display.update()
FPSCLOCK.tick(FPS)
def terminate():
pygame.quit()
sys.exit()
def checkForQuit():
for event in pygame.event.get(QUIT): # get all
the QUIT events
terminate() # terminate if any QUIT events are
present
for event in pygame.event.get(KEYUP): # get all
the KEYUP events
if event.key == K_ESCAPE:
terminate() # terminate if the KEYUP event was
for the Esc key
pygame.event.post(event) # put the other KEYUP
event objects back
def getStartingBoard():
# Return a board data structure with tiles in
the solved state.
# For example, if BOARDWIDTH and BOARDHEIGHT are
both 3, this function
# returns [[1, 4, 7], [2, 5, 8], [3, 6, BLANK]]
counter = 1
board = []
for x in range(BOARDWIDTH):
column = []
for y in range(BOARDHEIGHT):
column.append(counter)
counter += BOARDWIDTH
board.append(column)
counter -= BOARDWIDTH * (BOARDHEIGHT - 1) +
BOARDWIDTH - 1
board[BOARDWIDTH-1][BOARDHEIGHT-1] = BLANK
return board
def getBlankPosition(board):
# Return the x and y of board coordinates of the
blank space.
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
if board[x][y] == BLANK:
return (x, y)
def makeMove(board, move):
# This function does not check if the move is
valid.
blankx, blanky = getBlankPosition(board)
if move == UP:
board[blankx][blanky], board[blankx][blanky + 1]
= board[blankx][blanky + 1],
board[blankx][blanky]
elif move == DOWN:
board[blankx][blanky], board[blankx][blanky - 1]
= board[blankx][blanky - 1],
board[blankx][blanky]
elif move == LEFT:
board[blankx][blanky], board[blankx + 1][blanky]
= board[blankx + 1][blanky],
board[blankx][blanky]
elif move == RIGHT:
board[blankx][blanky], board[blankx - 1][blanky]
= board[blankx - 1][blanky],
board[blankx][blanky]
def isValidMove(board, move):
blankx, blanky = getBlankPosition(board)
return (move == UP and blanky != len(board[0]) -
1) or \
(move == DOWN and blanky != 0) or \
(move == LEFT and blankx != len(board) - 1) or \
(move == RIGHT and blankx != 0)
def getRandomMove(board, lastMove=None):
# start with a full list of all four moves
validMoves = [UP, DOWN, LEFT, RIGHT]
# remove moves from the list as they are
disqualified
if lastMove == UP or not isValidMove(board,
DOWN):
validMoves.remove(DOWN)
if lastMove == DOWN or not isValidMove(board,
UP):
validMoves.remove(UP)
if lastMove == LEFT or not isValidMove(board,
RIGHT):
validMoves.remove(RIGHT)
if lastMove == RIGHT or not isValidMove(board,
LEFT):
validMoves.remove(LEFT)
# return a random move from the list of
remaining moves
return random.choice(validMoves)
def getLeftTopOfTile(tileX, tileY):
left = XMARGIN + (tileX * TILESIZE) + (tileX -
1)
top = YMARGIN + (tileY * TILESIZE) + (tileY - 1)
return (left, top)
def getSpotClicked(board, x, y):
# from the x & y pixel coordinates, get the x &
y board coordinates
for tileX in range(len(board)):
for tileY in range(len(board[0])):
left, top = getLeftTopOfTile(tileX, tileY)
tileRect = pygame.Rect(left, top, TILESIZE,
TILESIZE)
if tileRect.collidepoint(x, y):
return (tileX, tileY)
return (None, None)
def drawTile(tilex, tiley, number, adjx=0, adjy=0):
# draw a tile at board coordinates tilex and
tiley, optionally a few
# pixels over (determined by adjx and adjy)
left, top = getLeftTopOfTile(tilex, tiley)
pygame.draw.rect(DISPLAYSURF, TILECOLOR, (left +
adjx, top + adjy, TILESIZE, TILESIZE))
textSurf = BASICFONT.render(str(number), True,
TEXTCOLOR)
textRect = textSurf.get_rect()
textRect.center = left + int(TILESIZE / 2) +
adjx, top + int(TILESIZE / 2) + adjy
DISPLAYSURF.blit(textSurf, textRect)
def makeText(text, color, bgcolor, top, left):
# create the Surface and Rect objects for some
text.
textSurf = BASICFONT.render(text, True, color,
bgcolor)
textRect = textSurf.get_rect()
textRect.topleft = (top, left)
return (textSurf, textRect)
def drawBoard(board, message):
DISPLAYSURF.fill(BGCOLOR)
if message:
textSurf, textRect = makeText(message,
MESSAGECOLOR, BGCOLOR, 5, 5)
DISPLAYSURF.blit(textSurf, textRect)
for tilex in range(len(board)):
for tiley in range(len(board[0])):
if board[tilex][tiley]:
drawTile(tilex, tiley, board[tilex][tiley])
left, top = getLeftTopOfTile(0, 0)
width = BOARDWIDTH * TILESIZE
height = BOARDHEIGHT * TILESIZE
pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (left
- 5, top - 5, width + 11, height + 11), 4)
DISPLAYSURF.blit(RESET_SURF, RESET_RECT)
DISPLAYSURF.blit(NEW_SURF, NEW_RECT)
DISPLAYSURF.blit(SOLVE_SURF, SOLVE_RECT)
def slideAnimation(board, direction, message,
animationSpeed):
# Note: This function does not check if the move
is valid.
blankx, blanky = getBlankPosition(board)
if direction == UP:
movex = blankx
movey = blanky + 1
elif direction == DOWN:
movex = blankx
movey = blanky - 1
elif direction == LEFT:
movex = blankx + 1
movey = blanky
elif direction == RIGHT:
movex = blankx - 1
movey = blanky
# prepare the base surface
drawBoard(board, message)
baseSurf = DISPLAYSURF.copy()
# draw a blank space over the moving tile on the
baseSurf Surface.
moveLeft, moveTop = getLeftTopOfTile(movex,
movey)
pygame.draw.rect(baseSurf, BGCOLOR, (moveLeft,
moveTop, TILESIZE, TILESIZE))
for i in range(0, TILESIZE, animationSpeed):
# animate the tile sliding over
checkForQuit()
DISPLAYSURF.blit(baseSurf, (0, 0))
if direction == UP:
drawTile(movex, movey, board[movex][movey], 0, -i)
if direction == DOWN:
drawTile(movex, movey, board[movex][movey], 0, i)
if direction == LEFT:
drawTile(movex, movey, board[movex][movey], -i,
0)
if direction == RIGHT:
drawTile(movex, movey, board[movex][movey], i,
0)
pygame.display.update()
FPSCLOCK.tick(FPS)
def generateNewPuzzle(numSlides):
# From a starting configuration, make numSlides
number of moves (and
# animate these moves).
sequence = []
board = getStartingBoard()
drawBoard(board, '')
pygame.display.update()
pygame.time.wait(500) # pause 500 milliseconds
for effect
lastMove = None
for i in range(numSlides):
move = getRandomMove(board, lastMove)
slideAnimation(board, move, 'Generating new
puzzle...', animationSpeed=int(TILESIZE / 3))
makeMove(board, move)
sequence.append(move)
lastMove = move
return (board, sequence)
def resetAnimation(board, allMoves):
# make all of the moves in allMoves in reverse.
revAllMoves = allMoves[:] # gets a copy of the
list
revAllMoves.reverse()
for move in revAllMoves:
if move == UP:
oppositeMove = DOWN
elif move == DOWN:
oppositeMove = UP
elif move == RIGHT:
oppositeMove = LEFT
elif move == LEFT:
oppositeMove = RIGHT
slideAnimation(board, oppositeMove, '',
animationSpeed=int(TILESIZE / 2))
makeMove(board, oppositeMove)
if __name__ == '__main__':
main() |
|
| | |
- Output:
|
| | |
| |
7- |
Python
program, Python Game - 2
|
|
|
|
|
- Python program, Python
program, Python Game - 2
- Create a new Python project In Visual Studio
2022
- the
Microsoft Visual Studio (... or 2019 or 2022) is
a powerful IDE for Python language
- Open/Run
Microsoft Visual Studio 2022
- To view
Python templates, search for python.
 |
Select the
Python
Application template, and select
Next. |
- Create a new Python project In
Visual Studio 2022
On the Configure your new project screen
- (specify a name and file location
for the project, and then select Create)
Project name:
PyGsnake2
Location:
C:\Users\...\source\repos
(default location for Visual
Studio 2022)
|
- The new project opens in Visual Studio
2022 - (Visual Studio 2022
Compiler - IDE, to compile Python project /
file )
- The
Visual Studio Solution Explorer window shows the
project structure
- Python
Project Properieties -
PyGsnake2
- Projct
Folder: C:\Users\...\source\repos\PyGsnake2
- Startup
File: PyGsnake2.py
- Project
file: PyGsnake2.sln
|
- Download Python
Project : PyGsnake2.zip -
(19.4 KB zip file)
Download
- Project
consist of:
One Python Form -
(PyGsnake2.py )
|
 | |
Download Python
Project : PyGsnake2.zip -
(10.4 KB zip file) Download
|
- Source Code:
Download this
Source Code at python file:
PyGsnake2.py - (4.54 KB Python
file) download
|
Download this
Source Code at txt file: PyGsnake2.txt - (4.54 KB
Python file) download |
 |
Continue
|
Python Code
to display Python Game
- (python file :PyGsnake2.py) | |
|
|
|
"""
Python Game
"""
try:
import pygame
pygame.init()
except:
print("----<error>-----\nSomething wrong with
pygame\nPlz run with Python 3 and make sure
pygame is installed")
input()
exit()
a = False
try:
import random
a = True
except:
print("----<error>-----\nProblem with imported
modules\nModules|Imported\nRandom |"+str(a)+"Please
fix")
class vr:
gw = 16
gh = 16
pxl = 32
sw = 0
sh = 0
points = 0
coloroffset = 4
done = False
vr.sw = vr.gw*vr.pxl
vr.sh = vr.gh*vr.pxl
#setup
clock = pygame.time.Clock()
screen = pygame.display.set_mode((vr.sw, vr.sh))
#pressed = pygame.key.get_pressed()
c = 0;
class apple:
x = 1
y = 1
lvl = 0
class snake:
##x first then y
leng = 4
x = 5
y = 16
dire = 1
speed = 60
tailx = []
taily = []
class gamef:
def grid():
ty = False
for x in range(int(vr.sw/vr.pxl)):
for y in range(int(vr.sh/vr.pxl)):
of = 0
if (y%2)==0:
of = 1
if (((x+of)%2)==0):
pygame.draw.rect(screen,
(32,32,32),pygame.Rect(x*vr.pxl,y*vr.pxl,vr.pxl,vr.pxl))
else:
pygame.draw.rect(screen,
(64,64,64),pygame.Rect(x*vr.pxl,y*vr.pxl,vr.pxl,vr.pxl))
ty = not ty
def draw():
#Framerate of 10
pygame.draw.rect(screen,
(128,128,128),pygame.Rect(0,0,vr.pxl,vr.sh))
pygame.draw.rect(screen,
(128,128,128),pygame.Rect(vr.sw-vr.pxl,0,vr.pxl,vr.sh))
pygame.draw.rect(screen,
(128,128,128),pygame.Rect(0,0,vr.sw,vr.pxl))
pygame.draw.rect(screen,
(128,128,128),pygame.Rect(0,vr.sh-vr.pxl,vr.sw,vr.pxl))
color=(0,255,0)
pygame.draw.rect(screen, color,
pygame.Rect(vr.pxl*apple.x+2,vr.pxl*apple.y+2,
vr.pxl-4, vr.pxl-4))
col = 0
os = vr.coloroffset
for i in range(len(snake.tailx)):
if (col+os >= 255):
os=-vr.coloroffset
elif(col+os<=0):
os=vr.coloroffset
col+=os
color = (col,col,255)
pygame.draw.rect(screen, color,
pygame.Rect(vr.pxl*snake.tailx[i],vr.pxl*snake.taily[i],
vr.pxl, vr.pxl))
color=(0,0,192)
pygame.draw.rect(screen, color,
pygame.Rect(vr.pxl*snake.x,vr.pxl*snake.y,
vr.pxl, vr.pxl))
def keyd():
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
snake.dire=0
if pressed[pygame.K_RIGHT]:
snake.dire=1
if pressed[pygame.K_DOWN]:
snake.dire=2
if pressed[pygame.K_LEFT]:
snake.dire=3
def ref():
gamef.tails()
if (snake.dire == 0):
gamef.move(0,-1)
#snake.y -=1
elif (snake.dire == 1):
gamef.move(1,0)
#snake.x+=1
elif (snake.dire == 2):
#snake.y+=1
gamef.move(0,1)
elif (snake.dire == 3):
gamef.move(-1,0)
#snake.x-=1
def move(x,y):
#x check
if (snake.x+x)>= vr.gw-1:
print ("out of bounds")
snake.x = 1;
elif(snake.x+x)<= 0:
print ("out of bounds")
snake.x = vr.gw-2;
else:
snake.x+=x
#y check
if (snake.y+y)>= vr.gh-1:
print ("out of bounds")
snake.y = 1;
elif(snake.y+y)<= 0:
print ("out of bounds")
snake.y = vr.gh-2;
else:
snake.y+=y
#apple
if (snake.x == apple.x) and (snake.y == apple.y):
snake.leng+=1
apple.lvl+=1
apple.x = random.randint(1,vr.gw-2)
apple.y = random.randint(1,vr.gh-2)
print("Apple pos:\nX - "+str(apple.x)+"\nY - "+str(apple.y))
def tails():
snake.tailx.append(snake.x)
snake.taily.append(snake.y)
if (len(snake.tailx) > snake.leng):
snake.tailx.pop(0)
snake.taily.pop(0)
while not vr.done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
vr.done = True
exit()
quit()
gamef.grid()
gamef.keyd()
c+=1
gamef.draw()
if (c >= (200/snake.speed)):
gamef.ref()
c=0
#snake.speed+=1
pygame.display.flip()
clock.tick(50) |
|
| | |
- Output:
 |
pic 1
|
 |
Pic 2 | | |
| | | |
|
|
|