Completely new set of materials for GUI class! Thanks Tony!!
This commit is contained in:
parent
ee0765c345
commit
8f7356f425
|
@ -0,0 +1,62 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
"""
|
||||
Demonstrates one way of embedding Matplotlib figures into a PySimpleGUI window.
|
||||
Adapted: From https://gitlab.com/lotspaih/PySimpleGUI/tree/master
|
||||
|
||||
Basic steps are:
|
||||
* Create a Canvas Element
|
||||
* Layout form
|
||||
* Display form (NON BLOCKING)
|
||||
* Draw plots onto convas
|
||||
* Display form (BLOCKING)
|
||||
"""
|
||||
|
||||
#No exactly sure how all this works, but taken from example given as a template.
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code ----------------------
|
||||
#see https://matplotlib.org/
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
#x-values
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
#y-values
|
||||
y = np.sin(x)
|
||||
plt.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
layout = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 3), size=(6, 2))]]
|
||||
|
||||
window = sg.Window('Matplot in PySimpleGUI', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
button, value = window.Read()
|
||||
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code --------------------
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
plt.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
|
||||
#centre bottom and left axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
layout = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib (axes centred)', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 3), size=(6, 2))]]
|
||||
|
||||
window = sg.Window('Matplot in PySimpleGUI', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
button, value = window.Read()
|
||||
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
"""
|
||||
Demonstrates one way of embedding Matplotlib figures into a PySimpleGUI window.
|
||||
|
||||
Basic steps are:
|
||||
* Create a Canvas Element
|
||||
* Layout form
|
||||
* Display form (NON BLOCKING)
|
||||
* Draw plots onto convas
|
||||
* Display form (BLOCKING)
|
||||
"""
|
||||
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code --------------------
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
plt.plot(x/np.pi,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
#centre bottom and left axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
#Format axes - nicer eh!
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
|
||||
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
layout = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib (axes pi format)', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 3), size=(6, 2))]]
|
||||
|
||||
window = sg.Window('Matplot in PySimpleGUI', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
button, value = window.Read()
|
||||
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code --------------------
|
||||
|
||||
def set_plot(amp, function):
|
||||
global figure_w, figure_h, fig
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
if function == 'sine':
|
||||
y= amp*np.sin(x)
|
||||
ax.set_title('sin(x)')
|
||||
else:
|
||||
y=amp*np.cos(x)
|
||||
ax.set_title('cos(x)')
|
||||
plt.plot(x/np.pi,y)
|
||||
|
||||
|
||||
#centre bottom and left axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
#Format axes - nicer eh!
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
|
||||
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
amp = 1
|
||||
function = 'sine'
|
||||
set_plot(amp, function)
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
#use Tabs - one for options, one for canvas to be displayed
|
||||
#set spinner for amplitude and combo for function type
|
||||
|
||||
tab1_layout = [[sg.Text('Select Amplitude and trig function type', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Spin([sz for sz in range (1,5)], initial_value =1, size = (2,1), key = '_spin_'),
|
||||
sg.Text('Amplitude', size = (10, 1), font = ('Calibri', 12, 'bold'))],
|
||||
[sg.InputCombo(['sine', 'cosine'], size = (8, 4), key = '_function_'),
|
||||
sg.Text('Function', size = (10, 1),font = ('Calibri', 12, 'bold'))],
|
||||
[sg.ReadButton('Redraw Plot')],
|
||||
[sg.Text('', size = (2, 25))]]
|
||||
|
||||
tab2_layout = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib and options', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 3), size=(6, 2))]]
|
||||
|
||||
layout = [[sg.TabGroup([[sg.Tab('Select options', tab1_layout), sg.Tab('Display Plot', tab2_layout)]])]]
|
||||
window = sg.Window('Matplot, PySimpleGUI and options', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button == 'Redraw Plot':
|
||||
amp = int(value['_spin_'])
|
||||
function = value['_function_']
|
||||
set_plot(amp,function)
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
if button is None:
|
||||
break
|
||||
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code --------------------
|
||||
|
||||
def set_plot(amp, function):
|
||||
global figure_w, figure_h, fig
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
if function == 'sine':
|
||||
y= amp*np.sin(x)
|
||||
ax.set_title('sin(x)')
|
||||
else:
|
||||
y=amp*np.cos(x)
|
||||
ax.set_title('cos(x)')
|
||||
plt.plot(x/np.pi,y)
|
||||
|
||||
|
||||
#centre bottom and left axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
#Format axes - nicer eh!
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
|
||||
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
amp = 1
|
||||
function = 'sine'
|
||||
set_plot(amp, function)
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
#using one window based on two columns instead of Tabs
|
||||
column1 = [[sg.Text('Select Amplitude and trig function type', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Spin([sz for sz in range (1,5)], initial_value =1, size = (2,1), key = '_spin_'),
|
||||
sg.Text('Amplitude', size = (10, 1), font = ('Calibri', 12, 'bold'))],
|
||||
[sg.InputCombo(['sine', 'cosine'], size = (8, 4), key = '_function_'),
|
||||
sg.Text('Function', size = (10, 1),font = ('Calibri', 12, 'bold'))],
|
||||
[sg.ReadButton('Redraw Plot')],
|
||||
[sg.Text('', size = (1, 27))]]
|
||||
|
||||
column2 = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib and options', font = ('Calibri', 18, 'bold'))],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 3), size=(6, 2))]]
|
||||
|
||||
layout = [[sg.Column(column1), sg.Column(column2)]]
|
||||
window = sg.Window('Matplot, PySimpleGUI and options', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button == 'Redraw Plot':
|
||||
amp = int(value['_spin_'])
|
||||
function = value['_function_']
|
||||
set_plot(amp,function)
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
if button is None:
|
||||
break
|
||||
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Oct 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.ticker as ticker
|
||||
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
|
||||
import matplotlib.backends.tkagg as tkagg
|
||||
import numpy as np
|
||||
import tkinter as tk
|
||||
|
||||
sg.ChangeLookAndFeel('Purple')
|
||||
sg.SetOptions(font = ('Calibri', 14, 'bold'))
|
||||
|
||||
def draw_figure(canvas, figure, loc = (0,0)):
|
||||
|
||||
figure_canvas_agg = FigureCanvasAgg(figure)
|
||||
figure_canvas_agg.draw()
|
||||
figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds
|
||||
figure_w, figure_h = int(figure_w), int(figure_h)
|
||||
photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)
|
||||
canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)
|
||||
tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)
|
||||
return photo
|
||||
|
||||
|
||||
#------------ Matplotlib code --------------------
|
||||
|
||||
def set_plot(a,b,c, function):
|
||||
global figure_w, figure_h, fig
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-10, 10, 100)
|
||||
if function == 'y = ax + b':
|
||||
y= a*x + b
|
||||
if a == 1:
|
||||
a = ''
|
||||
if a == -1:
|
||||
a = '-'
|
||||
title = str('y = ') + str(a) + 'x + ' + str(b)
|
||||
ax.set_title(title)
|
||||
else:
|
||||
y = a*x**2 + b*x + c
|
||||
#avoiding getting -1x or -1x**2 instead of -x for title
|
||||
if a == 1:
|
||||
a = ''
|
||||
if a == -1:
|
||||
a = '-'
|
||||
if b == 1:
|
||||
b = ''
|
||||
if b == -1:
|
||||
b = '-'
|
||||
title = str('y = ') + str(a) + 'x**2 + ' + str(b) + 'x + ' + str(c)
|
||||
ax.set_title(title)
|
||||
plt.plot(x,y)
|
||||
|
||||
|
||||
#centre bottom and left axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
|
||||
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds
|
||||
amp = 1
|
||||
function = 'y = ax + b'
|
||||
set_plot(1,1,1, function)
|
||||
|
||||
#------------End Matplotlib code --------------------
|
||||
|
||||
#column 1 for function type and constant values ...
|
||||
|
||||
column1 = [
|
||||
[sg.Text('Select constants and function type', )],
|
||||
[sg.InputCombo(['y = ax + b', 'y = ax^2 + bx + c'], size = (12, 4), key = '_function_'),
|
||||
sg.Text('Function', size = (10, 1))], [sg.Text('', size = (1, 2))],
|
||||
[sg.Spin([sz for sz in range (-6,6)], initial_value =1, size = (2,1), key = '_a_'),
|
||||
sg.Text('a', size = (3, 1)),
|
||||
sg.Spin([sz for sz in range (-6,6)], initial_value =1, size = (2,1), key = '_b_'),
|
||||
sg.Text('b', size = (3, 1)),
|
||||
sg.Spin([sz for sz in range (-6,6)], initial_value =1, size = (2,1), key = '_c_'),
|
||||
sg.Text('c', size = (3, 1))], [sg.Text('', size = (1, 1))],
|
||||
[sg.ReadButton('Redraw Plot')],
|
||||
[sg.Text('', size = (1, 14))]]
|
||||
|
||||
column2 = [[sg.Text('Plot Test - PySimpleGUI and Matplotlib and options')],
|
||||
[sg.Canvas(size = (figure_w, figure_h), key = '_canvas_')],
|
||||
[sg.OK(pad=((figure_w / 2, 0), 1), size=(4, 1))]]
|
||||
|
||||
layout = [[sg.Column(column1), sg.Column(column2)]]
|
||||
window = sg.Window('Matplot, PySimpleGUI and options', force_toplevel = True).Layout(layout).Finalize()
|
||||
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button == 'Redraw Plot':
|
||||
a = int(value['_a_'])
|
||||
b = int(value['_b_'])
|
||||
c = int(value['_c_'])
|
||||
function = value['_function_']
|
||||
set_plot(a,b,c,function)
|
||||
fig_photo = draw_figure(window.FindElement('_canvas_').TKCanvas, fig)
|
||||
|
||||
if button is None:
|
||||
break
|
||||
|
||||
|
|
@ -4,19 +4,23 @@
|
|||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
#layout, Text, Input,button on line below
|
||||
layout = [
|
||||
[sg.Text('Celcius'), sg.InputText()], #layout, Text, Input
|
||||
[sg.Submit()], #button on line below
|
||||
[sg.Text('Celcius'), sg.InputText()],
|
||||
[sg.Submit()],
|
||||
]
|
||||
|
||||
#setup window with Title
|
||||
window = sg.Window('Temperature Converter').Layout(layout)
|
||||
|
||||
button, value = window.Read() #get value (part of a list)
|
||||
#get value (part of a list)
|
||||
button, value = window.Read()
|
||||
|
||||
fahrenheit = round(9/5*float(value[0]) +32, 1) #convert and create string
|
||||
#convert and create string
|
||||
fahrenheit = round(9/5*float(value[0]) +32, 1)
|
||||
result = 'Temperature in Fahrenheit is: ' + str(fahrenheit)
|
||||
sg.Popup('Result', result) #display in Popup
|
||||
#display in Popup
|
||||
sg.Popup('Result', result)
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -19,14 +19,17 @@ sg.SetOptions (background_color = 'LightBlue',
|
|||
layout = [ [sg.Text('Enter a Temperature in Celcius')],
|
||||
[sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1))],
|
||||
[sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1))],
|
||||
[sg.ReadButton('Submit', bind_return_key = True)]] #Return = button press
|
||||
|
||||
[sg.ReadButton('Submit', bind_return_key = True)]]
|
||||
#Return = button press
|
||||
window = sg.Window('Converter').Layout(layout)
|
||||
|
||||
while True:
|
||||
button, value = window.Read() #get result
|
||||
if button is not None: #break out of loop is button not pressed.
|
||||
#get result
|
||||
button, value = window.Read()
|
||||
#break out of loop is button not pressed.
|
||||
if button is not None:
|
||||
fahrenheit = round(9/5*float(value[0]) +32, 1)
|
||||
window.FindElement(1).Update(fahrenheit) #put result in 2nd input box
|
||||
#put result in 2nd input box
|
||||
window.FindElement(1).Update(fahrenheit)
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -15,8 +15,8 @@ sg.SetOptions (background_color = 'LightBlue',
|
|||
#name inputs (key) uses dictionary- easy to see updating of results
|
||||
#value[input] first input value te c...
|
||||
layout = [ [sg.Text('Enter a Temperature in Celcius')],
|
||||
[sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = 'input')],
|
||||
[sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = 'result')],
|
||||
[sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = '_input_')],
|
||||
[sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = '_result_')],
|
||||
[sg.ReadButton('Submit', bind_return_key = True)]]
|
||||
|
||||
window = sg.FlexForm('Temp Converter').Layout(layout)
|
||||
|
@ -26,10 +26,11 @@ while True:
|
|||
if button is not None:
|
||||
#catch program errors for text or blank entry:
|
||||
try:
|
||||
fahrenheit = round(9/5*float(value['input']) +32, 1)
|
||||
window.FindElement('result').Update(fahrenheit) #put result in text box
|
||||
fahrenheit = round(9/5*float(value['_input_']) +32, 1)
|
||||
#put result in text box
|
||||
window.FindElement('_result_').Update(fahrenheit)
|
||||
except ValueError:
|
||||
sg.Popup('Error','Please try again') #display error
|
||||
sg.Popup('Error','Please try again')
|
||||
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -10,11 +10,11 @@ sg.SetOptions (font = ('Arial', 10, 'bold'))
|
|||
|
||||
|
||||
layout = [ [sg.Text('Enter a Temperature in Celcius')],
|
||||
[sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = 'input')],
|
||||
[sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = 'result')],
|
||||
[sg.Text('Celcius', size =(8,1)), sg.InputText(size = (15,1),key = '_input_')],
|
||||
[sg.Text('Result', size =(8,1)), sg.InputText(size = (15,1),key = '_result_')],
|
||||
[sg.ReadButton('Submit', bind_return_key = True)]]
|
||||
|
||||
window = sg.FlexForm('Temp Converter').Layout(layout)
|
||||
window = sg.Window('Temp Converter').Layout(layout)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
@ -22,13 +22,13 @@ while True:
|
|||
#catch program errors for text, floats or blank entry:
|
||||
#Also validation for range [0, 50]
|
||||
try:
|
||||
if float(value['input']) > 50 or float(value['input']) <0:
|
||||
if float(value['_input_']) > 50 or float(value['_input_']) <0:
|
||||
sg.Popup('Error','Out of range')
|
||||
else:
|
||||
fahrenheit = round(9/5*int(value['input']) +32, 1)
|
||||
window.FindElement('result').Update(fahrenheit) #put result in text box
|
||||
fahrenheit = round(9/5*int(value['_input_']) +32, 1)
|
||||
window.FindElement('_result_').Update(fahrenheit)
|
||||
except ValueError:
|
||||
sg.Popup('Error','Please try again') #display error
|
||||
sg.Popup('Error','Please try again')
|
||||
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -4,18 +4,20 @@
|
|||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.ChangeLookAndFeel('GreenTan') #Set colour scheme
|
||||
sg.SetOptions (font =('Calibri',12,'bold') ) #and font
|
||||
#Set colour scheme and font
|
||||
sg.ChangeLookAndFeel('GreenTan')
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
|
||||
#One checkbox and three radio buttons (grouped as 'Radio1'
|
||||
#One checkbox and three radio buttons (grouped as 'Radio1')
|
||||
#value[0] - checkbox, Value[1-3] radiobutton selection
|
||||
layout = [[sg.Text('Membership Calculator', font = ('Calibri', 16, 'bold'))],
|
||||
[sg.Checkbox(' Student? 10% off', size = (25,1)), #value[0]
|
||||
[sg.Checkbox(' Student? 10% off', size = (25,1)),
|
||||
sg.ReadButton('Display Cost', size = (14,1))],
|
||||
[sg.Radio('1 month $50', 'Radio1', default = True), #value[1]
|
||||
sg.Radio('3 months $100', 'Radio1'), #value[2]
|
||||
sg.Radio('1 year $300', 'Radio1')], #value[3]
|
||||
[sg.Radio('1 month $50', 'Radio1', default = True),
|
||||
sg.Radio('3 months $100', 'Radio1'),
|
||||
sg.Radio('1 year $300', 'Radio1')],
|
||||
[sg.Text('', size = (30,1), justification = 'center', font =('Calibri', 16, 'bold'), key = 'result')]]
|
||||
|
||||
window = sg.Window('Gym Membership').Layout(layout)
|
||||
|
@ -30,11 +32,13 @@ while True:
|
|||
else:
|
||||
cost = 300
|
||||
if value[0]:
|
||||
cost = cost*0.9 #apply discount
|
||||
#apply discount
|
||||
cost = cost*0.9
|
||||
|
||||
#format as currency $ symbol and 2 d.p. - make a string
|
||||
result = str(' Cost: ' + '${:.2f}'.format(cost))
|
||||
window.FindElement('result').Update(result) #put the result in Textbox
|
||||
#put the result in Textbox
|
||||
window.FindElement('result').Update(result)
|
||||
|
||||
else:
|
||||
break
|
|
@ -0,0 +1,42 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import os
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
#get pathname to current file
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
#add file name for image
|
||||
pathname = dirname + '\\Gym_Logo.png'
|
||||
|
||||
layout = [[sg.Image(pathname),sg.Text(' Membership Calculator', font = ('Calibri', 16, 'bold'))],
|
||||
[sg.Checkbox(' Student? 10% off', size = (25,1)),
|
||||
sg.ReadButton('Display Cost', size = (14,1))],
|
||||
[sg.Radio('1 month $50', 'Radio1', default = True),
|
||||
sg.Radio('3 months $100', 'Radio1'),
|
||||
sg.Radio('1 year $300', 'Radio1')],
|
||||
[sg.Text('', size = (30,1), justification = 'center', font =('Calibri', 16, 'bold'), key = 'result')]]
|
||||
|
||||
window = sg.Window('Gym Membership').Layout(layout)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if value[1]:
|
||||
cost = 50
|
||||
elif value[2]:
|
||||
cost = 100
|
||||
else:
|
||||
cost = 300
|
||||
if value[0]:
|
||||
cost = cost*0.9
|
||||
|
||||
#format as currency $ symbol and 2 d.p. - make a string
|
||||
result = str(' Cost: ' + '${:.2f}'.format(cost))
|
||||
window.FindElement('result').Update(result)
|
||||
|
||||
else:
|
||||
break
|
|
@ -1,3 +1,4 @@
|
|||
|
||||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
@ -19,7 +20,7 @@ layout = [
|
|||
sg.ReadButton('Add Data', font = ('Calibri', 12, 'bold'))],
|
||||
[sg.Text('_'*40)],
|
||||
[sg.Text(' Race Club Name Time')],
|
||||
[sg.Multiline(size =(40,6),key = 'Multiline')]
|
||||
[sg.Multiline(size =(40,6),key = '_multiline_')]
|
||||
]
|
||||
|
||||
window = sg.Window('Enter & Display Data').Layout(layout)
|
||||
|
@ -34,7 +35,7 @@ while True:
|
|||
S = S + ['{:^9s}{:<11s}{:<10s}{:>8s}'.format(value[0],value[1],value[2],value[3])]
|
||||
for s in S:
|
||||
string = string + s + '\n'
|
||||
window.FindElement('Multiline').Update(string)
|
||||
window.FindElement('_multiline_').Update(string)
|
||||
string =''
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -8,11 +8,11 @@ import PySimpleGUI as sg
|
|||
|
||||
column1 = [
|
||||
[sg.Text('Pick operation', size = (15,1), font = ('Calibri', 12, 'bold'))],
|
||||
[sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (10,6))],
|
||||
[sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (10,6))],
|
||||
[sg.Text('', size =(1,4))]]
|
||||
column2 = [
|
||||
[sg.ReadButton('Submit', font = ('Calibri', 12, 'bold'), button_color = ('White', 'Red'))],
|
||||
[sg.Text('Result:', font = ('Calibri', 12, 'bold'))],[sg.InputText(size = (12,1), key = 'result')]
|
||||
[sg.Text('Result:', font = ('Calibri', 12, 'bold'))],[sg.InputText(size = (12,1), key = '_result_')]
|
||||
]
|
||||
|
||||
|
||||
|
@ -20,7 +20,7 @@ layout = [
|
|||
[sg.Text('Slider and Combo box demo', font = ('Calibri', 14,'bold'))],
|
||||
[sg.Slider(range = (-9, 9),orientation = 'v', size = (5,20), default_value = 0),
|
||||
sg.Slider(range = (-9, 9),orientation = 'v', size = (5, 20), default_value = 0),
|
||||
sg.Text(' '), sg.Column(column1), sg.Column(column2)]]
|
||||
sg.Text(' '), sg.Column(column1), sg.Column(column2)]]
|
||||
|
||||
#added grab_anywhere to when moving slider, who window doesn't move.
|
||||
|
||||
|
@ -43,6 +43,6 @@ while True:
|
|||
result = 'NA'
|
||||
else:
|
||||
result = value[0] / value[1]
|
||||
window.FindElement('result').Update(result)
|
||||
window.FindElement('_result_').Update(result)
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -11,7 +11,7 @@ layout = [
|
|||
sg.Spin([sz for sz in range (-9,10)], size = (2,1), initial_value = 0),
|
||||
sg.Text('Pick operation ->', size = (15,1)),
|
||||
sg.InputCombo(['Add','Subtract','Multiply','Divide'], size = (8,6))],
|
||||
[sg.Text('Result: ')],[sg.InputText(size = (5,1), key = 'result'),
|
||||
[sg.Text('Result: ')],[sg.InputText(size = (5,1), key = '_result_'),
|
||||
sg.ReadButton('Calculate', button_color = ('White', 'Red'))]]
|
||||
|
||||
window = sg.Window('Enter & Display Data', grab_anywhere= False).Layout(layout)
|
||||
|
@ -34,6 +34,6 @@ while True:
|
|||
result = 'NA'
|
||||
else:
|
||||
result = round( val[0] / val[1], 3)
|
||||
window.FindElement('result').Update(result)
|
||||
window.FindElement('_result_').Update(result)
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -12,11 +12,12 @@ column1 = [
|
|||
[sg.InputText( size = (15,1), key = 'add'), sg.ReadButton('Add')],
|
||||
[sg.ReadButton('Delete selected entry')]]
|
||||
|
||||
List = ['Austalia', 'Canada', 'Greece'] #initial listbox entries
|
||||
#initial listbox entries
|
||||
List = ['Austalia', 'Canada', 'Greece']
|
||||
|
||||
#add initial List to listbox
|
||||
layout = [
|
||||
[sg.Listbox(values=[l for l in List], size = (30,8), key ='listbox'),
|
||||
[sg.Listbox(values=[l for l in List], size = (30,8), key ='_listbox_'),
|
||||
sg.Column(column1)]]
|
||||
|
||||
window = sg.Window('Listbox').Layout(layout)
|
||||
|
@ -24,16 +25,20 @@ window = sg.Window('Listbox').Layout(layout)
|
|||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
#value[listbox] returns a list
|
||||
if button == 'Delete selected entry': #using value[listbox][0] give the string
|
||||
if value['listbox'] == []: #ensure something is selected
|
||||
#value[listbox] returns a list
|
||||
#using value[listbox][0] gives the string
|
||||
if button == 'Delete selected entry':
|
||||
#ensure something is selected
|
||||
if value['_listbox_'] == []:
|
||||
sg.Popup('Error','You must select a Country')
|
||||
else:
|
||||
List.remove(value['listbox'][0]) #find and remove this
|
||||
#find and remove this
|
||||
List.remove(value['_listbox_'][0])
|
||||
if button == 'Add':
|
||||
List.append(value['add']) #add string in add box to list
|
||||
List.sort() #sort
|
||||
#add string in add box to list
|
||||
List.append(value['add'])
|
||||
List.sort()
|
||||
#update listbox
|
||||
window.FindElement('listbox').Update(List)
|
||||
window.FindElement('_listbox_').Update(List)
|
||||
else:
|
||||
break
|
||||
|
|
|
@ -1,130 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to sue in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List):
|
||||
global ListDisplayed #store list in Multiline text globally
|
||||
ListDisplayed = List
|
||||
display = ''
|
||||
for l in List: #add list elements with new line
|
||||
display = display + l + '\n'
|
||||
window.FindElement('display').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(Names):
|
||||
L = Names[:]
|
||||
L.sort() #inbuilt sort
|
||||
displayList(L)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def selSort(Names):
|
||||
L = Names[:]
|
||||
for i in range(len(L)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(L)):
|
||||
if L[j] < L[smallest]: #find smallest value
|
||||
smallest = j #swap it to front
|
||||
L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion
|
||||
displayList(L)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsortHolder(Names):
|
||||
L = Names[:] #pass List, first and last
|
||||
quick_sort(L, 0, len(L) -1) #Start process
|
||||
displayList(L)
|
||||
|
||||
def quick_sort(L, first, last): #Quicksort is a partition sort
|
||||
if first >= last:
|
||||
return L
|
||||
pivot = L[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while L[high] > pivot:
|
||||
high = high -1
|
||||
while L[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
L[high], L[low] = L[low], L[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(L, first, low -1) #continue splitting - sort small lsist
|
||||
quick_sort(L, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works fot ordered lists
|
||||
def binarySearch():
|
||||
L = ListDisplayed[:] #get List currently in multiline display
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
displayList(Names)
|
||||
if button == 'Default sort':
|
||||
default(Names)
|
||||
if button == 'Sort: selection':
|
||||
selSort(Names)
|
||||
if button == 'Sort: quick':
|
||||
qsortHolder(Names)
|
||||
if button == 'Linear Search':
|
||||
linearSearch()
|
||||
if button == 'Binary Search':
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = '_display1_'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = '_display2_')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = '_linear_'), sg.InputText(size = (14,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
sorted_names = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def display_list(list, display):
|
||||
names = ''
|
||||
for l in list: #add list elements with new line
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']: #Check each value
|
||||
found = True
|
||||
window.FindElement('_display1_').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('_display1_').Update(value['_linear_'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binary_search():
|
||||
l = sorted_names[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
#Start with found is False
|
||||
found = False
|
||||
while lo <= hi:
|
||||
#Start in middle
|
||||
mid = (lo + hi) //2
|
||||
#get the value from the search box
|
||||
if l[mid] == value['_binary_']:
|
||||
window.FindElement('_display2_').Update('Binary search\n' + l[mid] + ' found.')
|
||||
#If found display name and stop
|
||||
found = True
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
#Search in top half
|
||||
lo = mid + 1
|
||||
else:
|
||||
#Search in lower half
|
||||
hi = mid - 1
|
||||
#If we get to end - display not found
|
||||
if not found:
|
||||
window.FindElement('_display2_').Update(value['_binary_'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
#show names - unordered and sorted
|
||||
if button == 'Show Names':
|
||||
display_list(names,'_display1_')
|
||||
display_list(sorted_names, '_display2_')
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List, display):
|
||||
names = ''
|
||||
for l in List: #add list elements with new line
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display1').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display1').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display2').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'Linear Search': #Find and display
|
||||
linearSearch()
|
||||
if button == 'Binary Search': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = '_display1_'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = '_display2_')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = '_linear_'), sg.InputText(size = (14,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1),key = '_ls_'), sg.ReadButton('Binary Search', size = (14,1),key='_bs_')],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#finalize allows the disabling of the two buttons before .Read statement
|
||||
window.Finalize()
|
||||
window.FindElement('_ls_').Update(disabled = True)
|
||||
window.FindElement('_bs_').Update(disabled = True)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
sorted_names = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def display_list(list, display):
|
||||
names = ''
|
||||
#add list elements with new line
|
||||
for l in list:
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
#enable buttons now data loaded
|
||||
window.FindElement('_ls_').Update(disabled = False)
|
||||
window.FindElement('_bs_').Update(disabled = False)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
#Check each value
|
||||
if l == value['_linear_']:
|
||||
found = True
|
||||
window.FindElement('_display1_').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('_display1_').Update(value['_linear_'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binary_search():
|
||||
l = sorted_names[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
#Start with found is Flase
|
||||
found = False
|
||||
while lo <= hi:
|
||||
#Start in middle
|
||||
mid = (lo + hi) //2
|
||||
#get the value from the search box
|
||||
if l[mid] == value['_binary_']:
|
||||
window.FindElement('_display2_').Update('Binary search\n' + l[mid] + ' found.')
|
||||
#If found display and stop
|
||||
found = True
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
#Search in top half
|
||||
lo = mid + 1
|
||||
else:
|
||||
#Search in lower half
|
||||
hi = mid - 1
|
||||
#If we get to end - display not found
|
||||
if not found:
|
||||
window.FindElement('_display2_').Update(value['_binary_'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
#show names - unordered and sorted
|
||||
if button == 'Show Names':
|
||||
display_list(names,'_display1_')
|
||||
display_list(sorted_names, '_display2_')
|
||||
if button == '_ls_':
|
||||
linear_search()
|
||||
if button == '_bs_':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold')), sg.ReadButton('Show Names')],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1),key = 'ls'), sg.ReadButton('Binary Search', size = (14,1),key='bs')],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
window.Finalize() #finalize allows the disabling
|
||||
window.FindElement('ls').Update(disabled=True) #of the two buttons
|
||||
window.FindElement('bs').Update(disabled=True)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List, display):
|
||||
names = ''
|
||||
for l in List: #add list elements with new line
|
||||
names = names + l + '\n'
|
||||
window.FindElement(display).Update(names)
|
||||
window.FindElement('ls').Update(disabled=False) #enable buttons now
|
||||
window.FindElement('bs').Update(disabled=False) #now data loaded
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display1').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display1').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display2').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display2').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'ls': #Find and display
|
||||
linearSearch()
|
||||
if button == 'bs': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
|
||||
names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
name = ''
|
||||
for l in names:
|
||||
name = name + l + '\n'
|
||||
|
||||
sorted_names = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
sortname = ''
|
||||
for l in sorted_names:
|
||||
sortname = sortname + l +'\n'
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold'))],
|
||||
[sg.Text(name, size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color = 'White',key = '_display1_'),
|
||||
sg.Text(sortname, size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color = 'White',key = '_display2_')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = '_linear_'), sg.InputText(size = (14,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']:
|
||||
found = True
|
||||
sg.Popup('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
sg.Popup('Linear search\n' +(value['_linear_'] + ' was not found'))
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binary_search():
|
||||
l = sorted_names[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
found = False
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2
|
||||
if l[mid] == value['_binary_']:
|
||||
sg.Popup('Binary search\n' + l[mid] + ' found.')
|
||||
found = True
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
if not found:
|
||||
sg.Popup('Binary search\n' +(value['_binary_'] + ' was not found'))
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
if button == 'Show Names':
|
||||
display_list(names,'_display1_')
|
||||
display_list(sorted_names, '_display2_')
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
||||
|
|
@ -1,79 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
|
||||
Names = ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
names = ''
|
||||
for l in Names:
|
||||
names = names + l + '\n'
|
||||
|
||||
SortedNames = ['Andrea','Belinda','Deborah','Helen',
|
||||
'Jenny','Kylie','Meredith','Pauline',
|
||||
'Roberta','Wendy']
|
||||
|
||||
sortnames = ''
|
||||
for l in SortedNames:
|
||||
sortnames = sortnames + l +'\n'
|
||||
|
||||
layout =[[sg.Text('Search Demo', font =('Calibri', 18, 'bold'))],
|
||||
[sg.Text(names,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display1'),
|
||||
sg.Text(sortnames,size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display2')],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (14,1), key = 'linear'), sg.InputText(size = (14,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', bind_return_key=True, size = (13,1)), sg.ReadButton('Binary Search', size = (14,1))],
|
||||
]
|
||||
window = sg.Window('Search Demo').Layout(layout)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
sg.Popup('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
sg.Popup('Linear search\n' +(value['linear'] + ' was not found'))
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = SortedNames[:]
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
sg.Popup('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
sg.Popup('Binary search\n' +(value['binary'] + ' was not found'))
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
|
||||
if button is not None:
|
||||
if button == 'Show Names': #show names - unordered and sorted
|
||||
displayList(Names,'display1')
|
||||
displayList(SortedNames, 'display2')
|
||||
if button == 'Linear Search': #Find and display
|
||||
linearSearch()
|
||||
if button == 'Binary Search': #Find and display
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,137 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to use in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color = 'White',key = '_display_'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = '_linear_'), sg.Text(' '), sg.InputText(size = (13,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def display_list(list):
|
||||
#store list in Multiline text globally
|
||||
global list_displayed
|
||||
list_displayed = list
|
||||
display = ''
|
||||
#add list elements with new line
|
||||
for l in list:
|
||||
display = display + l + '\n'
|
||||
window.FindElement('_display_').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(names):
|
||||
l = names[:]
|
||||
l.sort()
|
||||
display_list(l)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def sel_sort(names):
|
||||
l = names[:]
|
||||
for i in range(len(l)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(l)):
|
||||
#find smallest value
|
||||
if l[j] < l[smallest]:
|
||||
#swap it to front
|
||||
smallest = j
|
||||
#repeat from next position
|
||||
l[smallest], l[i] = l[i], l[smallest]
|
||||
display_list(l)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsort_holder(names):
|
||||
l = names[:]
|
||||
#pass List, first and last
|
||||
quick_sort(l, 0, len(l) -1)
|
||||
display_list(l)
|
||||
#Quicksort is a partition sort
|
||||
def quick_sort(l, first, last):
|
||||
if first >= last:
|
||||
return l
|
||||
pivot = l[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while l[high] > pivot:
|
||||
high = high -1
|
||||
while l[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
l[high], l[low] = l[low], l[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
#continue splitting - sort small list
|
||||
quick_sort(l, first, low -1)
|
||||
quick_sort(l, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']:
|
||||
found = True
|
||||
window.FindElement('_display_').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('_display_').Update(value['_linear_'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binary_search():
|
||||
l= list_displayed[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
found = False
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2
|
||||
if l[mid] == value['_binary_']:
|
||||
window.FindElement('_display_').Update('Binary search\n' + l[mid] + ' found.')
|
||||
found = True
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
if not found:
|
||||
window.FindElement('_display_').Update(value['_binary_'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
display_list(names)
|
||||
if button == 'Default sort':
|
||||
default(names)
|
||||
if button == 'Sort: selection':
|
||||
sel_sort(names)
|
||||
if button == 'Sort: quick':
|
||||
qsort_holder(names)
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to sue in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List):
|
||||
global ListDisplayed #store list in Multiline text globally
|
||||
ListDisplayed = List
|
||||
display = ''
|
||||
for l in List: #add list elements with new line
|
||||
display = display + l + '\n'
|
||||
window.FindElement('display').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(Names):
|
||||
L = Names[:]
|
||||
L.sort() #inbuilt sort
|
||||
displayList(L)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def selSort(Names):
|
||||
L = Names[:]
|
||||
for i in range(len(L)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(L)):
|
||||
if L[j] < L[smallest]: #find smallest value
|
||||
smallest = j #swap it to front
|
||||
L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion
|
||||
displayList(L)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsortHolder(Names):
|
||||
L = Names[:] #pass List, first and last
|
||||
quick_sort(L, 0, len(L) -1) #Start process
|
||||
displayList(L)
|
||||
|
||||
def quick_sort(L, first, last): #Quicksort is a partition sort
|
||||
if first >= last:
|
||||
return L
|
||||
pivot = L[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while L[high] > pivot:
|
||||
high = high -1
|
||||
while L[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
L[high], L[low] = L[low], L[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(L, first, low -1) #continue splitting - sort small lsist
|
||||
quick_sort(L, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = ListDisplayed[:] #get List currently in multiline display
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
displayList(Names)
|
||||
if button == 'Default sort':
|
||||
default(Names)
|
||||
if button == 'Sort: selection':
|
||||
selSort(Names)
|
||||
if button == 'Sort: quick':
|
||||
qsortHolder(Names)
|
||||
if button == 'Linear Search':
|
||||
linearSearch()
|
||||
if button == 'Binary Search':
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Listbox(values =[''], size = (14, 11),font = ('Calibri', 12), background_color ='White',key = '_display_'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = '_linear_'), sg.Text(' '), sg.InputText(size = (13,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def display_list(list):
|
||||
global list_displayed
|
||||
#store list in Multiline text globally
|
||||
list_displayed = list
|
||||
#add list elements with new line
|
||||
values = [l for l in list]
|
||||
window.FindElement('_display_').Update(values)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(names):
|
||||
l = names[:]
|
||||
l.sort()
|
||||
display_list(l)
|
||||
|
||||
#Selection sort
|
||||
def sel_sort(names):
|
||||
l = names[:]
|
||||
for i in range(len(l)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(l)):
|
||||
if l[j] < l[smallest]:
|
||||
smallest = j
|
||||
l[smallest], l[i] = l[i], l[smallest]
|
||||
display_list(l)
|
||||
|
||||
#Quick sort
|
||||
def qsort_holder(names):
|
||||
l = names[:]
|
||||
quick_sort(l, 0, len(l) - 1)
|
||||
display_list(l)
|
||||
|
||||
def quick_sort(l, first, last):
|
||||
if first >= last:
|
||||
return l
|
||||
pivot = l[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while l[high] > pivot:
|
||||
high = high -1
|
||||
while l[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
l[high], l[low] = l[low], l[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(l, first, low -1)
|
||||
quick_sort(l, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']:
|
||||
found = True
|
||||
#Create list for display
|
||||
result = ['Linear search', l + ' found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
break
|
||||
if not found:
|
||||
#Create list for display
|
||||
result = [value['_linear_'], 'was not found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
|
||||
#Binary Search
|
||||
def binary_search():
|
||||
l = list_displayed[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
found = False
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2
|
||||
if l[mid] == value['_binary_']:
|
||||
#Create list for display
|
||||
result = ['Binary search', l[mid] + ' found.']
|
||||
window.FindElement('_display_').Update(result)
|
||||
found = True
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
if not found:
|
||||
#Create list for display
|
||||
result = [value['_binary_'], 'was not found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
display_list(names)
|
||||
if button == 'Default sort':
|
||||
default(names)
|
||||
if button == 'Sort: selection':
|
||||
sel_sort(names)
|
||||
if button == 'Sort: quick':
|
||||
qsort_holder(names)
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
|
@ -1,130 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
|
||||
#setup column (called column1) of buttons to sue in layout
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Text('',size = (14, 11),relief=sg.RELIEF_SOLID,font = ('Calibri', 12), background_color ='White',key = 'display'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = 'linear'), sg.Text(' '), sg.InputText(size = (13,1), key = 'binary')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#names for Demo, could be loaded from a file
|
||||
Names= ['Roberta', 'Kylie', 'Jenny', 'Helen',
|
||||
'Andrea', 'Meredith','Deborah','Pauline',
|
||||
'Belinda', 'Wendy']
|
||||
|
||||
#function to display list
|
||||
def displayList(List):
|
||||
global ListDisplayed #store list in Multiline text globally
|
||||
ListDisplayed = List
|
||||
display = ''
|
||||
for l in List: #add list elements with new line
|
||||
display = display + l + '\n'
|
||||
window.FindElement('display').Update(display)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(Names):
|
||||
L = Names[:]
|
||||
L.sort() #inbuilt sort
|
||||
displayList(L)
|
||||
|
||||
#Selection sort - See Janson Ch 7
|
||||
def selSort(Names):
|
||||
L = Names[:]
|
||||
for i in range(len(L)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(L)):
|
||||
if L[j] < L[smallest]: #find smallest value
|
||||
smallest = j #swap it to front
|
||||
L[smallest], L[i] = L[i], L[smallest] #repeat from next poistion
|
||||
displayList(L)
|
||||
|
||||
#Quick sort - See Janson Ch 7
|
||||
def qsortHolder(Names):
|
||||
L = Names[:] #pass List, first and last
|
||||
quick_sort(L, 0, len(L) -1) #Start process
|
||||
displayList(L)
|
||||
|
||||
def quick_sort(L, first, last): #Quicksort is a partition sort
|
||||
if first >= last:
|
||||
return L
|
||||
pivot = L[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while L[high] > pivot:
|
||||
high = high -1
|
||||
while L[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
L[high], L[low] = L[low], L[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(L, first, low -1) #continue splitting - sort small lsist
|
||||
quick_sort(L, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linearSearch():
|
||||
L = Names[:]
|
||||
found = False
|
||||
for l in L:
|
||||
if l == value['linear']: #Check each value
|
||||
found = True
|
||||
window.FindElement('display').Update('Linear search\n' + l + ' found.')
|
||||
break
|
||||
if not found:
|
||||
window.FindElement('display').Update(value['linear'] + ' was \nNot found')
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binarySearch():
|
||||
L = ListDisplayed[:] #get List currently in multiline display
|
||||
lo = 0
|
||||
hi = len(L)-1
|
||||
found = False #Start with found is Flase
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2 #Start in middle
|
||||
if L[mid] == value['binary']: #get the value from the search box
|
||||
window.FindElement('display').Update('Binary search\n' + L[mid] + ' found.')
|
||||
found = True #If found display
|
||||
break #and stop
|
||||
elif L[mid] < value['binary']:
|
||||
lo = mid + 1 #Search in top half
|
||||
else:
|
||||
hi = mid - 1 #Search in lower half
|
||||
if not found: #If we get to end - display not found
|
||||
window.FindElement('display').Update(value['binary'] + ' was \nNot found')
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
displayList(Names)
|
||||
if button == 'Default sort':
|
||||
default(Names)
|
||||
if button == 'Sort: selection':
|
||||
selSort(Names)
|
||||
if button == 'Sort: quick':
|
||||
qsortHolder(Names)
|
||||
if button == 'Linear Search':
|
||||
linearSearch()
|
||||
if button == 'Binary Search':
|
||||
binarySearch()
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import os
|
||||
|
||||
sg.SetOptions (font =('Calibri',12,'bold'))
|
||||
|
||||
#get pathname to current file
|
||||
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
pathname = dirname + '\\Names.txt' #original data
|
||||
spathname = dirname + '\\Names(sorted).txt' #sorted data
|
||||
|
||||
#Get data from file
|
||||
names = [line.strip() for line in open(pathname)]
|
||||
|
||||
column1 = [[sg.ReadButton('Original list', size = (13,1))],
|
||||
[sg.ReadButton('Default sort', size = (13,1))],
|
||||
[sg.ReadButton('Sort: selection',size = (13,1))],
|
||||
[sg.ReadButton('Sort: quick', size = (13,1))]]
|
||||
|
||||
layout =[[sg.Text('Search and Sort Demo', font =('Calibri', 20, 'bold'))],
|
||||
[sg.Listbox(values =[''], size = (14, 11),font = ('Calibri', 12), background_color ='White',key = '_display_'), sg.Column(column1)],
|
||||
[sg.Text('_'*32,font = ('Calibri', 12))],
|
||||
[sg.InputText(size = (13,1), key = '_linear_'), sg.Text(' '), sg.InputText(size = (13,1), key = '_binary_')],
|
||||
[sg.ReadButton('Linear Search', size = (13,1)), sg.Text(' '), sg.ReadButton('Binary Search', size = (13,1))],
|
||||
]
|
||||
|
||||
window = sg.Window('Search and Sort Demo').Layout(layout)
|
||||
|
||||
#function to display list
|
||||
def display_list(list):
|
||||
global list_displayed
|
||||
#store list in Multiline text globally
|
||||
list_displayed = list
|
||||
#add list elements with new line
|
||||
values = [l for l in list]
|
||||
window.FindElement('_display_').Update(values)
|
||||
|
||||
#use inbuilt python sort
|
||||
def default(names):
|
||||
l = names[:]
|
||||
l.sort()
|
||||
display_list(l)
|
||||
|
||||
#Selection sort
|
||||
def sel_sort(names):
|
||||
l = names[:]
|
||||
for i in range(len(l)):
|
||||
smallest = i
|
||||
for j in range(i+1, len(l)):
|
||||
if l[j] < l[smallest]:
|
||||
smallest = j
|
||||
l[smallest], l[i] = l[i], l[smallest]
|
||||
display_list(l)
|
||||
|
||||
#Quick sort
|
||||
def qsort_holder(names):
|
||||
l = names[:]
|
||||
quick_sort(l, 0, len(l) - 1)
|
||||
display_list(l)
|
||||
|
||||
def quick_sort(l, first, last):
|
||||
if first >= last:
|
||||
return l
|
||||
pivot = l[first]
|
||||
low = first
|
||||
high = last
|
||||
while low < high:
|
||||
while l[high] > pivot:
|
||||
high = high -1
|
||||
while l[low] < pivot:
|
||||
low = low + 1
|
||||
if low <= high:
|
||||
l[high], l[low] = l[low], l[high]
|
||||
low = low + 1
|
||||
high = high -1
|
||||
quick_sort(l, first, low -1)
|
||||
quick_sort(l, low, last)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']:
|
||||
found = True
|
||||
#Create list for display
|
||||
result = ['Linear search', l + ' found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
break
|
||||
if not found:
|
||||
#Create list for display
|
||||
result = [value['_linear_'], 'was not found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
|
||||
#Binary Search
|
||||
def binary_search():
|
||||
l = list_displayed[:]
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
found = False
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2
|
||||
if l[mid] == value['_binary_']:
|
||||
#Create list for display
|
||||
found = True
|
||||
result = ['Binary search', l[mid] + ' found.']
|
||||
window.FindElement('_display_').Update(result)
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
if not found:
|
||||
#Create list for display
|
||||
result = [value['_binary_'], 'was not found']
|
||||
window.FindElement('_display_').Update(result)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Original list':
|
||||
display_list(names)
|
||||
if button == 'Default sort':
|
||||
default(names)
|
||||
if button == 'Sort: selection':
|
||||
sel_sort(names)
|
||||
if button == 'Sort: quick':
|
||||
qsort_holder(names)
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
|
@ -10,14 +10,14 @@ sg.SetOptions(font = ('Calibri', 12, 'bold'))
|
|||
|
||||
layout = [
|
||||
[sg.Text('Enter a Name and four Marks')],
|
||||
[sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = 'name')],
|
||||
[sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = 'm1')],
|
||||
[sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = 'm2')],
|
||||
[sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = 'm3')],
|
||||
[sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = 'm4')],
|
||||
[sg.ReadButton('Save', size = (8,1),key = 'save'), sg.Text('Press to Save to file')],
|
||||
[sg.ReadButton('Display',size = (8,1), key = 'display'), sg.Text('To retrieve and Display')],
|
||||
[sg.Multiline(size = (28,4), key = 'multiline')]]
|
||||
[sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = '_name_')],
|
||||
[sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = '_m1_')],
|
||||
[sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = '_m2_')],
|
||||
[sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = '_m3_')],
|
||||
[sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = '_m4_')],
|
||||
[sg.ReadButton('Save', size = (8,1),key = '_save_'), sg.Text('Press to Save to file')],
|
||||
[sg.ReadButton('Display',size = (8,1), key = '_display_'), sg.Text('To retrieve and Display')],
|
||||
[sg.Multiline(size = (28,4), key = '_multiline_')]]
|
||||
|
||||
window = sg.Window('Simple Average Finder').Layout(layout)
|
||||
|
||||
|
@ -28,32 +28,36 @@ while True:
|
|||
#initialise variables
|
||||
total = 0.0
|
||||
index = ''
|
||||
Name = value['name'] #get name
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__)) #get pathname to current file
|
||||
pathname = dirname + '\\results.txt' #add desired file name for saving to path
|
||||
name = value['_name_']
|
||||
#get pathname to current file
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
#add desired file name for saving to path
|
||||
pathname = dirname + '\\results.txt'
|
||||
|
||||
#needs validation and try/catch error checking, will crash if blank or text entry for marks
|
||||
|
||||
if button == 'save':
|
||||
if button == '_save_':
|
||||
#create dictionary index _m1_ ... _m4_
|
||||
for i in range (1,5):
|
||||
index = 'm' + str(i) #create dictionary index m1 ... m4
|
||||
index = '_m' + str(i) + '_'
|
||||
total += float(value[index])
|
||||
average = total/4
|
||||
f = open(pathname, 'w') #open file and save
|
||||
print (Name, file = f)
|
||||
#open file and save
|
||||
f = open(pathname, 'w')
|
||||
print (name, file = f)
|
||||
print (total, file = f)
|
||||
print (average, file = f)
|
||||
f.close()
|
||||
|
||||
#some error checking for missing file needed here
|
||||
|
||||
if button == 'display':
|
||||
if button == '_display_':
|
||||
#This loads the file line by line into a list called data.
|
||||
#the strip() removes whitespaces from beginning and end of each line.
|
||||
data = [line.strip() for line in open(pathname)]
|
||||
#create single string to display in multiline object.
|
||||
string = 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2])
|
||||
window.FindElement('multiline').Update(string)
|
||||
window.FindElement('_multiline_').Update(string)
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import os #to work with windows OS
|
||||
|
||||
sg.ChangeLookAndFeel('Dark')
|
||||
sg.SetOptions(font = ('Calibri', 12, 'bold'))
|
||||
|
||||
layout = [
|
||||
[sg.Text('Enter a Name and four Marks')],
|
||||
[sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = '_name_')],
|
||||
[sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = '_m1_')],
|
||||
[sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = '_m2_')],
|
||||
[sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = '_m3_')],
|
||||
[sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = '_m4_')],
|
||||
[sg.ReadButton('Save', size = (8,1),key = '_save_'), sg.Text('Press to Save to file')],
|
||||
[sg.ReadButton('Display',size = (8,1), key = '_display_'), sg.Text('To retrieve and Display')],
|
||||
[sg.Multiline(size = (28,4), key = '_multiline_')]]
|
||||
|
||||
window = sg.Window('Simple Average Finder').Layout(layout)
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read() #value is a dictionary holding name and marks (4)
|
||||
if button is not None:
|
||||
#initialise variables
|
||||
total = 0.0
|
||||
index = ''
|
||||
name = value['_name_']
|
||||
#get pathname to current file
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
#add desired file name for saving to path
|
||||
pathname = dirname + '\\results.txt'
|
||||
#generic catch error - blanks or wrong data types
|
||||
try:
|
||||
if button == '_save_':
|
||||
for i in range (1,5):
|
||||
index = '_m' + str(i) + '_'
|
||||
|
||||
#Check for values between 0 and 100
|
||||
if float(value[index]) < 0 or float(value[index]) >100:
|
||||
sg.Popup('Out of Range', 'Enter Marks between 0 and 100')
|
||||
else:
|
||||
total += float(value[index])
|
||||
average = total/4
|
||||
f = open(pathname, 'w')
|
||||
print (name, file = f)
|
||||
print (total, file = f)
|
||||
print (average, file = f)
|
||||
f.close()
|
||||
except ValueError:
|
||||
sg.Popup('Error','Check entries and try again')
|
||||
|
||||
if button == '_display_':
|
||||
#This loads the file line by line into a list called data.
|
||||
#the strip() removes whitespaces from beginning and end of each line.
|
||||
try:
|
||||
data = [line.strip() for line in open(pathname)]
|
||||
#create single string to display in multiline object.
|
||||
string = 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2])
|
||||
window.FindElement('_multiline_').Update(string)
|
||||
except:
|
||||
sg.PopupError('Error', 'Problem finding or reading file')
|
||||
else:
|
||||
break
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
import os #to work with windows OS
|
||||
|
||||
sg.ChangeLookAndFeel('BlueMono')
|
||||
sg.SetOptions(font = ('Calibri', 12, 'bold'))
|
||||
|
||||
layout = [
|
||||
[sg.Text('Enter a Name and four Marks')],
|
||||
[sg.Text('Name:', size =(10,1)), sg.InputText(size = (12,1), key = '_name_')],
|
||||
[sg.Text('Mark1:', size =(10,1)), sg.InputText(size = (6,1), key = '_m1_')],
|
||||
[sg.Text('Mark2:', size =(10,1)), sg.InputText(size = (6,1), key = '_m2_')],
|
||||
[sg.Text('Mark3:', size =(10,1)), sg.InputText(size = (6,1), key = '_m3_')],
|
||||
[sg.Text('Mark4:', size =(10,1)), sg.InputText(size = (6,1), key = '_m4_')],
|
||||
[sg.ReadButton('Save', size = (8,1),key = '_save_'), sg.Text('Press to Save to file')],
|
||||
[sg.ReadButton('Display',size = (8,1), key = '_display_'), sg.Text('To retrieve and Display')],
|
||||
[sg.Multiline(size = (28,4), key = '_multiline_')]]
|
||||
|
||||
window = sg.Window('Simple Average Finder').Layout(layout)
|
||||
|
||||
|
||||
while True:
|
||||
button, value = window.Read() #value is a dictionary holding name and marks (4)
|
||||
if button is not None:
|
||||
#initialise variables
|
||||
total = 0.0
|
||||
index = ''
|
||||
name = value['_name_']
|
||||
#get pathname to current file
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
#add desired file name for saving to path
|
||||
pathname = dirname + '\\results.txt'
|
||||
#generic catch error - blanks or wrong data types
|
||||
try:
|
||||
if button == '_save_':
|
||||
for i in range (1,5):
|
||||
index = '_m' + str(i) + '_'
|
||||
|
||||
#Check for values between 0 and 100
|
||||
if float(value[index]) < 0 or float(value[index]) >100:
|
||||
sg.Popup('Out of Range', 'Enter Marks between 0 and 100')
|
||||
else:
|
||||
total += float(value[index])
|
||||
average = total/4
|
||||
#check location and file name for file, no_window so go straight to folder selection
|
||||
|
||||
foldername = sg.PopupGetFolder('', no_window=True)
|
||||
filename = sg.PopupGetFile('Please enter a file name for your results')
|
||||
pathname = foldername + '\\' + filename + '.txt'
|
||||
|
||||
f = open(pathname, 'w')
|
||||
print (name, file = f)
|
||||
print (total, file = f)
|
||||
print (average, file = f)
|
||||
f.close()
|
||||
except ValueError:
|
||||
sg.Popup('Error','Check entries and try again')
|
||||
|
||||
if button == '_display_':
|
||||
#get pathname: folder and file
|
||||
pathname = sg.PopupGetFile('file to open', no_window=True, file_types=(("text files","*.txt"),))
|
||||
#This loads the file line by line into a list called data.
|
||||
#the strip() removes whitespaces from beginning and end of each line.
|
||||
try:
|
||||
data = [line.strip() for line in open(pathname)]
|
||||
#create single string to display in multiline object.
|
||||
string = 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2])
|
||||
window.FindElement('_multiline_').Update(string)
|
||||
except:
|
||||
sg.PopupError('Error', 'Problem finding or reading file')
|
||||
else:
|
||||
break
|
||||
|
|
@ -10,13 +10,15 @@ from matplotlib.ticker import MaxNLocator
|
|||
x=[]
|
||||
y=[]
|
||||
|
||||
with open('weight 20182.csv', 'r', encoding = 'utf-8-sig') as csvfile:
|
||||
with open('weight 2018.csv', 'r', encoding = 'utf-8-sig') as csvfile:
|
||||
plots = csv.reader(csvfile)
|
||||
for data in plots:
|
||||
var1 = (data[0]) #get heading for x and y axes
|
||||
#get heading for x and y axes
|
||||
var1 = (data[0])
|
||||
var2 = (data[1])
|
||||
break
|
||||
for data in plots: #get values - add to x list and y list
|
||||
for data in plots:
|
||||
#get values - add to x list and y list
|
||||
x.append(data[0])
|
||||
y.append(float(data[1]))
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
|
||||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
#Based of Example program from MikeTheWatchGuy
|
||||
#https://gitlab.com/lotspaih/PySimpleGUI
|
||||
|
||||
import sys
|
||||
import PySimpleGUI as sg
|
||||
import csv
|
||||
sg.ChangeLookAndFeel('BrownBlue')
|
||||
|
||||
def calc_ladder():
|
||||
|
||||
filename = sg.PopupGetFile('Get required file', no_window = True,file_types=(("CSV Files","*.csv"),))
|
||||
#populate table with file contents
|
||||
#Assume we know csv has heading in row 1
|
||||
#Assume we know 7 columns of data - relevenat to AFL w/o Pts or % shown
|
||||
#data is a list of lists containing data about each team
|
||||
#data[0] is one teams data data[0[[0] = team, data[0][1] P, data[0] [2] W,
|
||||
#data[0][3] L, data [0][4] D, data [0][5] F, data [0][6] A
|
||||
#no error checking or validation used.
|
||||
|
||||
#initialise variable
|
||||
data = []
|
||||
header_list = []
|
||||
#read csv
|
||||
with open(filename, "r") as infile:
|
||||
reader = csv.reader(infile)
|
||||
for i in range (1):
|
||||
#get headings
|
||||
header = next(reader)
|
||||
#read everything else into a list of rows
|
||||
data = list(reader)
|
||||
#add headings
|
||||
header = header + ['%', 'Pts']
|
||||
for i in range (len(data)):
|
||||
#calculate % and format to 2 decimal places
|
||||
percent = str('{:.2f}'.format(int(data[i][5])/int(data[i][6])*100))
|
||||
data[i] = data[i] + [percent] #add to data
|
||||
pts = int(data[i][2])*4 + int(data[i][4])*2
|
||||
data[i] = data[i] + [pts] #add to data
|
||||
|
||||
|
||||
#use Table (explore settings) and add to column layout
|
||||
col_layout = [[sg.Table(values=data, headings=header, auto_size_columns=True,
|
||||
max_col_width = 12,justification='right', size=(None, len(data)))]]
|
||||
|
||||
layout = [[sg.Column(col_layout, size=(500,400), scrollable=True)],]
|
||||
|
||||
window = sg.Window('Table', location = (700, 325), grab_anywhere=False).Layout(layout)
|
||||
b, v = window.Read()
|
||||
|
||||
slayout = [[sg.Text('Load AFL file to display results with points and percentage'),sg.ReadButton('Load File', size = (20,1))]]
|
||||
swindow = sg.Window('Load File', location = (700,250)).Layout(slayout)
|
||||
|
||||
while True:
|
||||
button, value = swindow.Read()
|
||||
if button == 'Load File':
|
||||
calc_ladder()
|
|
@ -1,41 +0,0 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
#Based of Example program from MikeTheWatchGuy
|
||||
#https://gitlab.com/lotspaih/PySimpleGUI
|
||||
|
||||
import sys
|
||||
import PySimpleGUI as sg
|
||||
import csv
|
||||
|
||||
def table_example():
|
||||
filename = sg.PopupGetFile('filename to open', no_window=True, file_types=(("CSV Files","*.csv"),))
|
||||
#populate table with file contents
|
||||
#Assume we know csv has haeding in row 1
|
||||
#assume we know 7 columns of data - relevenat to AFL w/o Pts or % shown
|
||||
#data will be data[0] = team, data [1] P, data [2] W, data[3] L
|
||||
#data [4] D, data[5] F, data[6] A
|
||||
#no error checking or validation used.
|
||||
|
||||
data = []
|
||||
header_list = []
|
||||
with open(filename, "r") as infile:
|
||||
reader = csv.reader(infile)
|
||||
for i in range (1): #get headings
|
||||
header = next(reader)
|
||||
data = list(reader) # read everything else into a list of rows
|
||||
|
||||
|
||||
col_layout = [[sg.Table(values=data, headings=header, max_col_width=25,
|
||||
auto_size_columns=True, justification='right', size=(None, len(data)))]]
|
||||
|
||||
canvas_size = (13*10*len(header), 600) # estimate canvas size - 13 pixels per char * 10 char per column * num columns
|
||||
layout = [[sg.Column(col_layout, size=canvas_size, scrollable=True)],]
|
||||
|
||||
window = sg.Window('Table', grab_anywhere=False).Layout(layout)
|
||||
b, v = window.Read()
|
||||
|
||||
sys.exit(69)
|
||||
|
||||
table_example()
|
|
@ -0,0 +1,66 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
#Based of Example program from MikeTheWatchGuy
|
||||
#https://gitlab.com/lotspaih/PySimpleGUI
|
||||
|
||||
import sys
|
||||
import PySimpleGUI as sg
|
||||
import csv
|
||||
import operator
|
||||
|
||||
sg.ChangeLookAndFeel('Dark')
|
||||
|
||||
def table_example():
|
||||
|
||||
filename = sg.PopupGetFile('Get required file', no_window = True,file_types=(("CSV Files","*.csv"),))
|
||||
#populate table with file contents
|
||||
#Assume we know csv has heading in row 1
|
||||
#Assume we know 7 columns of data - relevenat to AFL w/o Pts or % shown
|
||||
#data is a list of lists containing data about each team
|
||||
#data[0] is one teams data data[0[[0] = team, data[0][1] P, data[0] [2] W,
|
||||
#data[0][3] L, data [0][4] D, data [0][5] F, data [0][6] A
|
||||
#no error checking or validation used.
|
||||
|
||||
#initialise variables
|
||||
data = []
|
||||
header_list = []
|
||||
with open(filename, "r") as infile:
|
||||
reader = csv.reader(infile)
|
||||
for i in range (1):
|
||||
header = next(reader)
|
||||
data = list(reader)
|
||||
header = header + ['%', 'Pts']
|
||||
for i in range (len(data)):
|
||||
#calculate %
|
||||
percent = int(data[i][5])/int(data[i][6])*100
|
||||
data[i] = data[i] + [percent]
|
||||
pts = int(data[i][2])*4 + int(data[i][4])*2
|
||||
data[i] = data[i] + [pts]
|
||||
#sort data
|
||||
#first by %
|
||||
data.sort(key = operator.itemgetter(7), reverse = True)
|
||||
#then by pts
|
||||
data.sort(key = operator.itemgetter(8), reverse = True)
|
||||
#and format string to 2 decimal places
|
||||
for i in range(len(data)):
|
||||
data[i][7] = str('{:.2f}'.format(data[i][7]))
|
||||
#use Table (explore settings) and add to column layout
|
||||
col_layout = [[sg.Table(values=data, headings=header, auto_size_columns=True,
|
||||
max_col_width = 12,justification='right', size=(None, len(data)))]]
|
||||
#experimented with size and location to get windows to fit :-)
|
||||
#remove titlebar of main display window
|
||||
|
||||
layout = [[sg.Column(col_layout, size=(415,400), scrollable=True)],]
|
||||
window = sg.Window('Table', location = (662, 320), no_titlebar=True, grab_anywhere=False).Layout(layout)
|
||||
b, v = window.Read()
|
||||
|
||||
slayout = [[sg.Text(' Load AFL (csv) file to display results.', font = ('Calibri', 14, 'bold') ),
|
||||
sg.ReadButton('Load File', size = (14,1))]]
|
||||
swindow = sg.Window('Load File', location = (654,250)).Layout(slayout)
|
||||
|
||||
while True:
|
||||
button, value = swindow.Read()
|
||||
if button == 'Load File':
|
||||
table_example()
|
|
@ -0,0 +1,59 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
#Based of Example program from MikeTheWatchGuy
|
||||
#https://gitlab.com/lotspaih/PySimpleGUI
|
||||
|
||||
import sys
|
||||
import PySimpleGUI as sg
|
||||
import csv
|
||||
import operator
|
||||
import os
|
||||
|
||||
#get pathname to current file and add file name for image
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
pathname = dirname + '\\AFL.png'
|
||||
|
||||
def table_example():
|
||||
|
||||
filename = sg.PopupGetFile('Get required file', no_window = True,file_types=(("CSV Files","*.csv"),))
|
||||
|
||||
|
||||
data = []
|
||||
header_list = []
|
||||
|
||||
with open(filename, "r") as infile:
|
||||
reader = csv.reader(infile)
|
||||
for i in range (1):
|
||||
header = next(reader)
|
||||
data = list(reader)
|
||||
header = header + ['%', 'Pts']
|
||||
for i in range (len(data)):
|
||||
|
||||
percent = int(data[i][5])/int(data[i][6])*100
|
||||
data[i] = data[i] + [percent]
|
||||
pts = int(data[i][2])*4 + int(data[i][4])*2
|
||||
data[i] = data[i] + [pts]
|
||||
|
||||
data.sort(key = operator.itemgetter(7), reverse = True)
|
||||
data.sort(key = operator.itemgetter(8), reverse = True)
|
||||
|
||||
for i in range(len(data)):
|
||||
data[i][7] = str('{:.2f}'.format(data[i][7]))
|
||||
|
||||
col_layout = [[sg.Table(values=data, headings=header, auto_size_columns=True,
|
||||
max_col_width = 12,justification='right', size=(None, len(data)))]]
|
||||
|
||||
layout = [[sg.Column(col_layout, size=(443,400), scrollable=True)],]
|
||||
window = sg.Window('Table', location = (662, 328), no_titlebar=True, grab_anywhere=False).Layout(layout)
|
||||
b, v = window.Read()
|
||||
|
||||
slayout = [[sg.Image(pathname),sg.Text('Load AFL data to display results.', font = ('Calibri', 14, 'bold') ),
|
||||
sg.ReadButton('Load File', size = (14,1))]]
|
||||
swindow = sg.Window('Load File', location = (654,250)).Layout(slayout)
|
||||
|
||||
while True:
|
||||
button, value = swindow.Read()
|
||||
if button == 'Load File':
|
||||
table_example()
|
|
@ -0,0 +1,47 @@
|
|||
#PySimple examples (v 3.8)
|
||||
#Tony Crewe
|
||||
#Sep 2018
|
||||
|
||||
import PySimpleGUI as sg
|
||||
|
||||
sg.ChangeLookAndFeel('SandyBeach')
|
||||
sg.SetOptions (font = ('Calibri', 12, 'bold'))
|
||||
|
||||
|
||||
|
||||
layout0 = [[sg.ReadButton('Show/Hide window1'),sg.ReadButton('Show/Hide window2')]]
|
||||
|
||||
layout1 =[[ sg.Text('window1')], [sg.Multiline( size = (35, 10))]]
|
||||
layout2 =[[ sg.Text('window2')], [sg.Multiline( size = (35, 10))]]
|
||||
window0 = sg.Window('Home Window', location = (400, 150)).Layout(layout0)
|
||||
|
||||
window1 = sg.Window('Window1', location = (400, 250)).Layout(layout1).Finalize()
|
||||
window1.Hide()
|
||||
w1 = False
|
||||
|
||||
window2 = sg.Window('Window2', location = (800, 250)).Layout(layout2).Finalize()
|
||||
window2.Hide()
|
||||
w2 = False
|
||||
|
||||
while True:
|
||||
button, v = window0.Read()
|
||||
if button is not None:
|
||||
if button =='Show/Hide window1':
|
||||
if w1 == True:
|
||||
window1.Hide()
|
||||
w1 = False
|
||||
else:
|
||||
window1.UnHide()
|
||||
w1=True
|
||||
if button =='Show/Hide window2':
|
||||
if w2 == True:
|
||||
window2.Hide()
|
||||
w2 = False
|
||||
else:
|
||||
window2.UnHide()
|
||||
w2=True
|
||||
else:
|
||||
break
|
||||
|
||||
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Sep 2017 - updated Sep 2018
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
import PySimpleGUI as sg
|
||||
|
||||
tab1_layout = [[sg.Text('This is inside tab 1')]]
|
||||
|
||||
tab2_layout = [[sg.Text('This is inside tab 2')]]
|
||||
|
||||
layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout),
|
||||
sg.Tab('Tab 2', tab2_layout)]])],
|
||||
[sg.ReadButton('Read')]]
|
||||
|
||||
window = sg.Window('Main Window').Layout(layout)
|
||||
|
||||
while True:
|
||||
b, v = window.Read()
|
||||
if b is not None:
|
||||
print(b,v)
|
||||
else:
|
||||
break
|
|
@ -1,27 +0,0 @@
|
|||
#matplotlib, numpy, pyplot
|
||||
#Tony Crewe
|
||||
#Sep 2017 - updated Sep 2018import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
#centre bottom and keft axes to zero
|
||||
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
import PySimpleGUI as sg
|
||||
import os
|
||||
|
||||
sg.ChangeLookAndFeel('BlueMono')
|
||||
|
||||
#get pathname to current file
|
||||
|
||||
dirname, filename = os.path.split(os.path.abspath(__file__))
|
||||
pathname = dirname + '\\Names.txt'
|
||||
spathname = dirname + '\\Names(sorted).txt'
|
||||
#Get data from file
|
||||
names = [line.strip() for line in open(pathname)]
|
||||
sorted_names = names[:]
|
||||
sorted_names.sort()
|
||||
|
||||
tab1_layout =[[sg.Text('Linear Search Demo', font =('Calibri', 14, 'bold'))],
|
||||
[sg.Listbox(values =[n for n in names], size = (15, 12),font = ('Calibri', 12), background_color ='White',key = '_display1_')],
|
||||
[sg.Text('_'*15,font = ('Calibri', 12))],
|
||||
[sg.Text('Enter name to search for:')],
|
||||
[sg.InputText(size = (18,1), key = '_linear_')],
|
||||
[sg.ReadButton('Linear Search', size = (15,1))]]
|
||||
|
||||
tab2_layout = [[sg.Text('Binary Search Demo', font =('Calibri', 14, 'bold'))],
|
||||
[sg.Listbox(values =[n for n in sorted_names], size = (15, 12),font = ('Calibri', 12), background_color ='White',key = '_display2_')],
|
||||
[sg.Text('_'*18,font = ('Calibri', 12))],
|
||||
[sg.Text('Enter name to search for:')],
|
||||
[sg.InputText(size = (18,1), key = '_binary_')],
|
||||
[sg.ReadButton('Binary Search', size = (15,1))]]
|
||||
|
||||
layout = [
|
||||
[sg.TabGroup([[sg.Tab('Linear Search', tab1_layout),sg.Tab('Binary Search', tab2_layout)]])]]
|
||||
|
||||
window = sg.Window('Main Window').Layout(layout)
|
||||
|
||||
#Linear Search - no need for Ordered list
|
||||
def linear_search():
|
||||
l = names[:]
|
||||
found = False
|
||||
for l in l:
|
||||
if l == value['_linear_']: #Check each value
|
||||
found = True
|
||||
result = ['Linear search', l + ' found']
|
||||
window.FindElement('_display1_').Update(result)
|
||||
break
|
||||
if not found:
|
||||
result = [value['_linear_'], 'was not found']
|
||||
window.FindElement('_display1_').Update(result)
|
||||
|
||||
#Binary Search - only works for ordered lists
|
||||
def binary_search():
|
||||
l = sorted_names
|
||||
lo = 0
|
||||
hi = len(l)-1
|
||||
found = False
|
||||
while lo <= hi:
|
||||
mid = (lo + hi) //2
|
||||
if l[mid] == value['_binary_']:
|
||||
found = True
|
||||
result = ['Binary search', l[mid] + ' found.']
|
||||
window.FindElement('_display2_').Update(result)
|
||||
break
|
||||
elif l[mid] < value['_binary_']:
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
if not found:
|
||||
result = [value['_binary_'], 'was not found']
|
||||
window.FindElement('_display2_').Update(result)
|
||||
|
||||
while True:
|
||||
button, value = window.Read()
|
||||
if button is not None:
|
||||
if button == 'Linear Search':
|
||||
linear_search()
|
||||
if button == 'Binary Search':
|
||||
binary_search()
|
||||
else:
|
||||
break
|
|
@ -1,28 +0,0 @@
|
|||
#Plt using matplylib, plotly and numpy
|
||||
#Tony Crewe
|
||||
#Sep 2017 updated Sep 2018
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import matplotlib.ticker as ticker
|
||||
|
||||
fig=plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
x = np.linspace(-np.pi*2, np.pi*2, 100)
|
||||
y= np.sin(x)
|
||||
ax.plot(x/np.pi,y)
|
||||
|
||||
ax.set_title('sin(x)')
|
||||
ax.spines['left'].set_position('zero')
|
||||
ax.spines['right'].set_color('none')
|
||||
ax.spines['bottom'].set_position('zero')
|
||||
ax.spines['top'].set_color('none')
|
||||
|
||||
#Format axes - nicer eh!
|
||||
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%g $\pi$'))
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
|
||||
|
Binary file not shown.
After Width: | Height: | Size: 6.9 KiB |
|
@ -0,0 +1,19 @@
|
|||
Team,P,W,L,D,F,A
|
||||
Adelaide Crows,22,12,10,0,1941,1865
|
||||
Brisbane Lions,22,5,17,0,1825,2049
|
||||
Carlton,22,2,20,0,1353,2282
|
||||
Collingwood,22,15,7,0,2046,1699
|
||||
Essendon,22,12,10,0,1932,1838
|
||||
Fremantle,22,8,14,0,1556,2041
|
||||
Geelong Cats,22,13,9,0,2045,1554
|
||||
Gold Coast Suns,22,4,18,0,1308,2182
|
||||
GWS Giants,22,13,8,1,1898,1661
|
||||
Hawthorn,22,15,7,0,1972,1642
|
||||
Melbourne,22,14,8,0,2299,1749
|
||||
North Melbourne,22,12,10,0,1950,1790
|
||||
Port Adelaide,22,12,10,0,1780,1654
|
||||
Richmond,22,18,4,0,2143,1574
|
||||
St Kilda,22,4,17,1,1606,2125
|
||||
Sydney Swans,22,14,8,0,1822,1664
|
||||
West Coast Eagles,22,16,6,0,2012,1657
|
||||
Western Bulldogs,22,8,14,0,1575,2037
|
|
|
@ -0,0 +1,19 @@
|
|||
Team,P,W,L,D,F,A
|
||||
Richmond,22,18,4,0,2143,1574
|
||||
West Coast Eagles,22,16,6,0,2012,1657
|
||||
Collingwood,22,15,7,0,2046,1699
|
||||
Hawthorn,22,15,7,0,1972,1642
|
||||
Melbourne,22,14,8,0,2299,1749
|
||||
Sydney Swans,22,14,8,0,1822,1664
|
||||
GWS Giants,22,13,8,1,1898,1661
|
||||
Geelong Cats,22,13,9,0,2045,1554
|
||||
North Melbourne,22,12,10,0,1950,1790
|
||||
Port Adelaide,22,12,10,0,1780,1654
|
||||
Essendon,22,12,10,0,1932,1838
|
||||
Adelaide Crows,22,12,10,0,1941,1865
|
||||
Western Bulldogs,22,8,14,0,1575,2037
|
||||
Fremantle,22,8,14,0,1556,2041
|
||||
Brisbane Lions,22,5,17,0,1825,2049
|
||||
St Kilda,22,4,17,1,1606,2125
|
||||
Gold Coast Suns,22,4,18,0,1308,2182
|
||||
Carlton,22,2,20,0,1353,2282
|
|
Binary file not shown.
After Width: | Height: | Size: 14 KiB |
|
@ -0,0 +1,10 @@
|
|||
Andrea
|
||||
Belinda
|
||||
Deborah
|
||||
Helen
|
||||
Jenny
|
||||
Kylie
|
||||
Meredith
|
||||
Pauline
|
||||
Roberta
|
||||
Wendy
|
|
@ -0,0 +1,10 @@
|
|||
Roberta
|
||||
Kylie
|
||||
Jenny
|
||||
Helen
|
||||
Andrea
|
||||
Meredith
|
||||
Deborah
|
||||
Pauline
|
||||
Belinda
|
||||
Wendy
|
|
@ -1,88 +0,0 @@
|
|||
# TCC
|
||||
#20/1/18 Oz date
|
||||
|
||||
from tkinter import *
|
||||
|
||||
def callback(event): #used to allow Return key as well as
|
||||
calculate() # button press for mark entry
|
||||
|
||||
|
||||
def calculate():
|
||||
global i, total,name
|
||||
name = entry_name.get() #get the name and prevent another
|
||||
mark[i] = entry_mark.get()
|
||||
label_name.configure(state = DISABLED)
|
||||
entry_name.configure(state = DISABLED)
|
||||
mark[i] = entry_mark.get() #get and store in mark list and clear entry
|
||||
entry_mark.delete(0,END)
|
||||
i = i + 1 #get total i - needs to be global
|
||||
if i == 4: #if four marks - stop
|
||||
button_done.configure(state = NORMAL)
|
||||
button_calculate.configure(state = DISABLED)
|
||||
|
||||
def done():
|
||||
total = 0
|
||||
for m in mark: #total marks - convery to integer
|
||||
total += int(m)
|
||||
average = total/4 #calculate average
|
||||
f = open(pathname, 'w')
|
||||
print(name, file= f)
|
||||
print(total, file= f) #write to file
|
||||
print(average, file= f)
|
||||
f.close()
|
||||
button_done.configure(state = DISABLED) #stop button being pressed again
|
||||
button_display.configure(state = NORMAL)
|
||||
|
||||
|
||||
def display():
|
||||
#create list of three valuesand combine elemnets into one string - use \n for new line
|
||||
data = [line.strip() for line in open(pathname)]
|
||||
s= 'Name: ' + data[0] +'\nTotal: ' + str(data[1]) + '\nAverage: ' + str(data[2])
|
||||
label_displayresults.configure(text = s)
|
||||
|
||||
|
||||
root = Tk()
|
||||
root.title('text files')
|
||||
|
||||
#set up controls
|
||||
label_instructs = Label(justify = LEFT, padx = 10, pady=10,width = 30, height =4, text = 'Enter a Name then a Mark then press\nCalculate, do this 4 times.Then press\nDone to Save Name, Total and Average.')
|
||||
label_name = Label(text='Name: ', width = 8)
|
||||
entry_name = Entry(width = 8)
|
||||
label_mark = Label(text='Mark: ', width = 8)
|
||||
entry_mark = Entry(width = 8)
|
||||
button_calculate = Button(text = 'Calculate', command=calculate)
|
||||
button_done= Button(pady = 8, text='Done', command = done, state = DISABLED)
|
||||
button_display = Button(pady =8,text = 'Display', command=display, state = DISABLED)
|
||||
label_displaytext = Label(justify = LEFT, text='Press display to\nretrieve recent\nTotal & Average')
|
||||
label_displayresults=Label(justify = LEFT, padx = 10, height = 5,)
|
||||
|
||||
#set up positioning of controls
|
||||
label_instructs.grid(row = 0, columnspan = 3)
|
||||
label_name.grid(row = 1, column = 0)
|
||||
entry_name.grid(row = 1, column = 1)
|
||||
label_mark.grid(row = 2, column = 0)
|
||||
entry_mark.grid(row = 2, column = 1)
|
||||
|
||||
entry_mark.bind('<Return>', callback) #create binding for Return key for mark entry box
|
||||
|
||||
button_calculate.grid(row =3, column = 0)
|
||||
button_done.grid(row = 3, column = 1)
|
||||
button_display.grid(row = 4, column = 0)
|
||||
label_displaytext.grid(row = 4, column = 1)
|
||||
label_displayresults.grid(row = 5, columnspan = 2)
|
||||
|
||||
#global variables when used in more than one function
|
||||
global i
|
||||
global mark
|
||||
global total
|
||||
global average
|
||||
i=total=0
|
||||
mark = [0,0,0,0]
|
||||
average = 0.0
|
||||
entry_name.focus() #set initial focus
|
||||
|
||||
global pathname
|
||||
|
||||
pathname = "C:\\Users\\tcrewe\\Dropbox\\01 Teaching folders\\07 TCC Python stuff\\TCC py files\\TCC sample files\wordlist.txt"
|
||||
|
||||
mainloop()
|
|
@ -0,0 +1,3 @@
|
|||
Tony
|
||||
275.0
|
||||
68.75
|
Binary file not shown.
After Width: | Height: | Size: 23 KiB |
|
@ -0,0 +1,3 @@
|
|||
Jill
|
||||
314.0
|
||||
78.5
|
|
@ -0,0 +1,98 @@
|
|||
Date,Weight (kg)
|
||||
29-Dec,94.5
|
||||
30-Dec,94
|
||||
31-Dec,94
|
||||
1-Jan,93.5
|
||||
2-Jan,94.2
|
||||
3-Jan,94
|
||||
4-Jan,94
|
||||
5-Jan,93.4
|
||||
6-Jan,92.6
|
||||
7-Jan,93.1
|
||||
8-Jan,92.7
|
||||
9-Jan,92.5
|
||||
10-Jan,92.3
|
||||
11-Jan,92.1
|
||||
12-Jan,92.5
|
||||
13-Jan,92.6
|
||||
14-Jan,92.5
|
||||
15-Jan,92.1
|
||||
16-Jan,91.6
|
||||
17-Jan,91.3
|
||||
18-Jan,91.8
|
||||
19-Jan,91.7
|
||||
20-Jan,91.9
|
||||
21-Jan,91.8
|
||||
22-Jan,91.1
|
||||
23-Jan,90.7
|
||||
24-Jan,90.5
|
||||
25-Jan,90.5
|
||||
26-Jan,90.3
|
||||
27-Jan,90.1
|
||||
28-Jan,89.9
|
||||
29-Jan,90.2
|
||||
30-Jan,90.1
|
||||
31-Jan,89.9
|
||||
1-Feb,89.5
|
||||
2-Feb,89.1
|
||||
3-Feb,89.3
|
||||
4-Feb,89.4
|
||||
5-Feb,89.2
|
||||
6-Feb,88.2
|
||||
7-Feb,88.2
|
||||
8-Feb,88.3
|
||||
9-Feb,88.2
|
||||
10-Feb,89.1
|
||||
11-Feb,88.9
|
||||
12-Feb,88.6
|
||||
13-Feb,88.7
|
||||
14-Feb,88.5
|
||||
15-Feb,88.1
|
||||
16-Feb,87.8
|
||||
17-Feb,87.9
|
||||
18-Feb,88.1
|
||||
19-Feb,87.9
|
||||
20-Feb,87.6
|
||||
21-Feb,87.5
|
||||
22-Feb,87.3
|
||||
23-Feb,87
|
||||
24-Feb,87.5
|
||||
25-Feb,87.7
|
||||
26-Feb,87.4
|
||||
27-Feb,87.2
|
||||
28-Feb,86.9
|
||||
1-Mar,86.9
|
||||
2-Mar,86.9
|
||||
3-Mar,86.5
|
||||
4-Mar,86.8
|
||||
5-Mar,87
|
||||
6-Mar,86.9
|
||||
7-Mar,86.2
|
||||
8-Mar,86.4
|
||||
9-Mar,86.1
|
||||
10-Mar,86.7
|
||||
11-Mar,85.6
|
||||
12-Mar,85.8
|
||||
13-Mar,85.3
|
||||
14-Mar,85.1
|
||||
15-Mar,85.4
|
||||
16-Mar,84.5
|
||||
17-Mar,85.1
|
||||
18-Mar,84.8
|
||||
19-Mar,84.8
|
||||
20-Mar,84.8
|
||||
21-Mar,84.9
|
||||
22-Mar,85.5
|
||||
23-Mar,85.1
|
||||
24-Mar,85.5
|
||||
25-Mar,85.6
|
||||
26-Mar,85.9
|
||||
27-Mar,85.9
|
||||
28-Mar,85.5
|
||||
29-Mar,85.9
|
||||
30-Mar,85.5
|
||||
1-Apr,85.2
|
||||
2-Apr,84.8
|
||||
3-Apr,85.3
|
||||
4-Apr,85.4
|
||||
5-Apr,85.3
|
|
Loading…
Reference in New Issue