Site Sponsors:
"Just Do It:" Graphical Command-Line Parameters for Python 3 
There seems to be a huge line between those who want to use console applications, and those who have the need for a GUI.

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


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

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

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

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

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

@staticmethod
def Begin(*fields, title="Input"):
''' Create the frame, add the title, as well as the input fields.'''
from collections import OrderedDict
self = Prompter()
self.tk = Tk()

self._dict = OrderedDict()

if title:
self.tk.title(title)

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

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

self._dict[ref]=obj
self.last_row += 1
return self

@staticmethod
def End(prompter):
''' Add the closing buttons, center, and pack the Frame.'''
if prompter.last_row is None:
return False
if isinstance(prompter, Prompter) is False:
return False
# zButtons (A Frame in the grid, plus the properly-centered pair of buttons)
bottom = Frame(prompter.tk)
bottom.grid(row=prompter.last_row, columnspan=2)
btn = Button(bottom, text="Okay", command=prompter._okay)
btn.pack(side=LEFT)

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

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

def show(self):
from collections import OrderedDict
self.tk.mainloop()
try:
results = OrderedDict()
if self._isOk is not True:
return results

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

@staticmethod
def Prompt(*fields, title="Input"):
''' Basic mission statement completed. '''
self = Prompter.Begin(*fields, title)
if Prompter.End(self) is False:
raise Exception("AddButtons: Unexpected Error.")
return self.show()


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


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


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


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

WIPI Results


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

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

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

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


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



[ view entry ] ( 628 views )   |  permalink  |  related link
zPython Clock, Revisited 
Here is an upgrade for zClock:



from tkinter import *
import time

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

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

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

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


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


zTimer()
zProgram.mainloop()


Here is zVideo :-)


[ view entry ] ( 530 views )   |  permalink  |  related link
zClock: Python3 Clock in 11 Statements 
When the atomic clock went on the fritz lately (probably was the first popular commercial version ever available!) I went lookin'.

Finding a few for under $20, it occurred to me that - attached as we are to the DST-capable world-time-zone, that I could easily slap one together in Python.



Looking for a way to keep braggin' over how easy it is to get things done using Python 3, I decided to see just how few lines I could use to encode the idea.

Here is what I came up with:

from tkinter import *
import time


zProgram = Tk()
zProgram.title("zClock: Python3 Clock in 11 Statements")
zClock = Label(zProgram,
font=('ariel', 72, 'bold'),
bg='gold',
fg='white')
zClock.pack(fill=BOTH, expand=1)


def zTimer():
zClock.config(text=time.strftime('%H:%M:%S'))
zClock.after(500, zTimer)


zTimer()
zProgram.mainloop()


While I could have written the above in even fewer lines using Turtle Graphics, having just cobbled-together a training offering on the same I thought that using TK would make for a refreshingly different blog post.


Here is a link to zVideo :-)


Enjoy the Journey!

-Rn

p.s: Feel free to add more features (date, day... temperature probe support for your Raspberry Pi) as your time and obsession(s) may allow.



[ view entry ] ( 369 views )   |  permalink  |  related link

<<First <Back | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Next> Last>>