
It creates the window, adds the labels, entries and button, connects them with focus / confirm commands and then centres the screen. When the credentials are submitted, it calls the login method.
The source for it is:
1 #! /usr/bin/env python3
2
3 from tkinter import *
4 from tkinter.ttk import *
5
6 def centred_win(root, width=400, height=300):
7 screen_width = root.winfo_screenwidth()
8 screen_height = root.winfo_screenheight()
9 x = (screen_width/2) - (width/2)
10 y = (screen_height/2) - (height/2)
11 root.geometry('%dx%d+%d+%d' % (width, height, x, y))
12
13 root = Tk()
14 centred_win(root, 500, 300)
15 root.mainloop()

1 from tkinter import *Explanation of the code:
2 from tkinter.ttk import *
3
4 class root_window_with_popup(Tk):
5 def __init__(self):
6 Tk.__init__(self)
7 self.geometry('400x300')
8 self.title(__file__)
9
10 self.label = Label(self, text='Right click to show popup')
11 self.label.pack(anchor = N, fill=NONE, expand=YES, pady = 40)
12
13 self.popup = Menu(self, tearoff=0)
14 self.popup.add_command(label="Quit", command=self.destroy)
15
16 self.bind("<button-3>", self.do_popup)
17
18 self.mainloop()
19
20 def do_popup(self, event):
21 self.popup.tk_popup(event.x_root, event.y_root, 0)
22
23 if __name__ == '__main__':
24 root_window_with_popup()

The above code does the following things:from tkinter.ttk import *
class App(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title(__file__)
self.master.geometry('400x300')
self.pack()
self.mainloop()
if __name__ == '__main__':
App()

Explanation of the above code:from tkinter import *
from tkinter.ttk import *
class App(Frame):
def __init__(self):
Frame.__init__(self)
self.master.geometry('400x300')
self.master.title(__file__)
self.pack()
self.menu = Menu(tearoff=False)
self.master.config(menu = self.menu)
fm = self.file_menu = None
fm = Menu(self.menu, tearoff=False)
self.menu.add_cascade(label='File', menu = fm)
fm.add_command(label='Say Hello', command = self.say_hello)
fm.add_separator()
fm.add_command(label='Quit', command = self.quit)
self.mainloop()
def say_hello(self, *e):
self.label = Label(self.master, text='Hello there!')
self.label.pack(anchor=CENTER, fill=NONE, expand=YES, side=LEFT)
if __name__ == '__main__':
App()
#! /usr/bin/env python3
# include tkinter packages
from tkinter import *
from tkinter.ttk import *
# create tk root class
root = Tk()
# create frame, add title and setup grid
frame = Frame(root, padding='3 3 12 12')
frame.master.title('Feet to meters')
frame.grid(column=0, row=0, sticky=NW)
frame.grid_columnconfigure(0, weight=1)
frame.grid_rowconfigure(0, weight=1)
# text entry
frame.feet = Entry(frame, width=7)
frame.feet.grid(column=2, row=1, sticky=W)
# calculated meters label
frame.meters = Label(frame, text='')
frame.meters.grid(column=2, row=2, sticky=W)
# calculate callback
def calculate(*e):
try:
frame.meters.config(
text = str(0.3048 * int(frame.feet.get()) *
10000.0/10000.0))
except:
frame.meters.config(text="")
# calculate button
frame.calc = Button(frame, text='Calculate', command = calculate)
frame.calc.grid(column=3, row=3, sticky=W)
# feet label
frame.flbl = Label(frame, text='feet')
frame.flbl.grid(column=3, row=1, sticky=W)
# is eq label
frame.islbl = Label(frame, text='is equivalent to')
frame.islbl.grid(column=1, row=2, sticky=E)
# meters label
frame.mlbl = Label(frame, text='meters')
frame.mlbl.grid(column=3, row=2, sticky=W)
# distance the widgets a bit
for w in frame.children.values():
w.grid(padx=5, pady=5)
# set focus to feet entry
frame.feet.focus()
# bindto calculate
frame.calc.bind("<Return>", calculate)
# enter main loop
root.mainloop()
Difficulty: Easy
Requirements: Python 3.1+ interpreter compiled with tkinter

Example 2: More minimised version#! /usr/bin/env python3
"""
Minimal ttk application that only displays an empty window and runs the main loop.
What's it doing:
1. Create root frame
2. Run application main loop
"""
from tkinter import ttk
frame = ttk.Frame()
frame.mainloop()
from tkinter import ttk
ttk.Frame().mainloop()
__import__('tkinter', fromlist=['ttk']).Frame().mainloop()
echo "__import__('tkinter', fromlist=['ttk']).Frame().mainloop()" | python3
echo hello
cp foo bar
rsync -av /myhome /backup_drive
echo 'and so forth'
#! /usr/bin/env python3
"""
Terminal command shortcut scirpt.
This script reads a command data file (~/.scdata) and executes commands from it.
There are two command execution models:
1. by argement, if you invoke it with a number, it executes this command
and exits. If you invoke it with -e opion, it opens the command file
for editing and then enters the main loop.
2. by loop, if you invoke it withouth an argument, it prints the
availible commands and promts for command number (id) to execute.
There are also 2 special non-numeric loop commands:
e: edit command file and return to main loop
q: quit program
"""
import os, sys, time
def get_editor():
try:
editor = os.environ['EDITOR']
except:
editor = 'vim'
return editor
def read_data(editor, data_file):
try:
with open(data_file, 'r') as f:
data = f.readlines()
data = [item.strip() for item in data]
data = dict(enumerate(data))
return data
except:
print('Data file not found, first start?.. Creating data file')
print('Please add some command to it..')
time.sleep(3)
with open(data_file, 'w') as f:
pass
os.system(editor + ' ' + data_file)
return read_data()
if __name__ == '__main__':
editor = get_editor()
data_file = os.path.join(os.path.expanduser('~'), '.scdata')
data = read_data(editor, data_file)
if len(sys.argv) > 1:
if sys.argv[1] == '-e':
print('Opening data file for editing..')
time.sleep(1)
os.system(editor + ' ' + data_file)
try:
cmd_task = int(sys.argv[1])
os.system('clear')
print('executing ', data[cmd_task], '\n')
os.system(data[cmd_task])
print('\nexecution done, exiting..')
sys.exit()
except (IndexError, ValueError):
pass
while True:
os.system('clear')
print('Shell command shortcut utility\n' +
'==============================\n\n' +
'Currently availible commands are:\n')
for cmd_task, cmd in data.items():
print(cmd_task, '\t', cmd)
print('\nPlease enter a command (e, q, or number)\n')
try:
cmd_task = input('% ')
if cmd_task == 'e':
os.system(editor + ' ' + data_file)
data = read_data(editor, data_file)
continue
elif cmd_task == 'q':
print('Quit.. bye!')
sys.exit()
else:
cmd_task = int(cmd_task)
assert(cmd_task <= len(data))
except (AssertionError, ValueError, KeyError):
print('Please enter a valid input ' +
'(h, e, q or number)')
time.sleep(1)
else:
os.system('clear')
print('executing \'{1}\' ..\n'.format(data[cmd_task]))
time.sleep(1)
os.system(data[cmd_task])
print('\nexecution done, hit a key to return..')
input()
#! /usr/bin/env python3
import os, sys, time
def dprint (message, delay=0.1):
"""
Prints message with delay between each character.
"""
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(delay)
if __name__ == '__main__':
"""
Demonstration logic.
"""
os.system('clear')
dprint('This message is printed slowly and demonstrates the slow\n' +
'print function.')
#! /bin/bash
mm_decho ()
{
local i stepping
stepping="0.01"
# When first argument is empty or not given, it just echoes a new line
# and leaves.
if [ ! "$1" ]; then
echo
return
fi
# If a second argument is given (delay stepping), check it for validity
# (if it is a float) and set stepping according to the argument.
if (( $# > 1 )) &&
[[ ($2 = $(echo $2 | grep -oE '[[:digit:]]')) ||
($2 = $(echo $2 | grep -oE '[[:digit:]]+\.[[:digit:]]+')) ]]
then
stepping="$2"
# In case the previous test failed, but we have a second argument,
# meaning it is invalid, just print the message, complain a bit and then
# quit the function with false.
elif (( $# > 1 )); then
echo "$1"
echo ".! mm_decho() oops: second argument is invalid!" 1>&2
echo ".! must be /float but is: \"$2\", leaving function.." 1>&2
return false 2>/dev/null
fi
# Do delayed printing of first input argument. Calculate the
# length of first arg. and substract one. Then make it a /for/
# sequence going through all the characters of the string,
# printing these and wait the delay stepping time.
for i in $(seq 0 $((${#1}-1))); do
echo -n "${1:$i:1}"
sleep $stepping
done
echo
}
mm_decho "Should be ok, default.."
mm_decho "Should be ok, costume stepping.." "0.05" "some more arg"
mm_decho "Should be ok, costume stepping.." "0.05"
mm_decho "" "0.3"
#! /usr/bin/env python3
"""
Linux / *NIX daemon base code.
This script daemonizes its self with the start option and kills an already
running daemon with the stop option. It's kept minimal and simple, but it works
and can be extended/re-factored as base-code for a useful daemon.
Note: point of daemons is that they are quite and run in the background, add
some logging if you are developing a daemon, saves a lot of headaches.
"""
import os, sys, signal
PIDFILE = '/tmp/mydaemon.pid'
def daemonize(pidfile, workpath='/'):
pid = os.fork()
if pid > 0:
sys.exit(0)
os.chdir(workpath)
os.setsid()
os.umask(0)
pid = os.fork()
if pid > 0:
sys.exit(0)
sys.stdout.flush()
sys.stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
pid = str(os.getpid())
with open(pidfile,'w+') as f:
f.write(pid + '\n')
def cleanup_handler(signum, frame):
os.remove(PIDFILE)
if __name__ == '__main__':
if sys.argv[1] == 'start':
if os.path.isfile(PIDFILE):
sys.stderr.write(
'pidfile found, daemon already running?\n')
sys.exit(2)
signal.signal(signal.SIGTERM, cleanup_handler)
daemonize(PIDFILE)
# daemon program logic
signal.pause()
elif sys.argv[1] == 'stop':
try:
with open(PIDFILE,'r') as pf:
pid = int(pf.read().strip())
except:
raise Exception('no pid found, daemon not running?')
os.kill(pid, signal.SIGTERM)
#! /usr/bin/env python3
"""
Work session start/end script.
This script contains the routines that should be performed before and after a
work session and log it. Currently these are git repository integrity checking
for start up. Change commiting and backup for end of session.
Uses 'rsync' for backup and 'git' for revision control, make sure they are in
place.
The BACKUP_PATH has to be adapted to the syncronization target.
This script is quite safe to use.
"""
import os, sys, subprocess, time, datetime
BACKUP_PATH = '/media/disk'
LOGFILE = 'session.log'
def log(message, logfile=LOGFILE):
timestamp = str(int(time.mktime(datetime.datetime.now().timetuple())))
name = os.path.basename(__file__)
with open(logfile, 'a') as f:
f.write('[' + timestamp + '] ' + name + ': ' + message + '\n')
def start():
status = subprocess.call(['git', 'gc'])
if status != 0:
print ('!! something went wrong with the repository checking!')
print ('(recheck manually with git fsck and restore integrity)')
sys.exit(1)
log('session started')
def end():
os.system('git add .')
os.system('git gui')
if os.path.isdir(BACKUP_PATH):
os.system('rsync -a . ' + BACKUP_PATH)
else:
print('backup path not existent, backup aborted..')
log('session ended')
if __name__ == '__main__':
usage = ('Usage: session.py start|end\n' +
' start: start session\n' +
' end: end session\n')
os.chdir(os.path.abspath(os.path.dirname(__file__)))
if len(sys.argv) == 1 or (
sys.argv[1] != 'start' and sys.argv[1] != 'end'):
print(usage)
sys.exit()
if sys.argv[1] == 'start':
start()
elif sys.argv[1] == 'end':
end()
#! /usr/bin/env python3
"""
Clean script based on .gitignore file, the 'find' and 'rm' command. It has to
be located in the same directory as the .gitignore file.
This script reads the .gitignore file, parses the patterns found there to a
shell remove command and then executes it.
- With the 'dirs' option it also removes directories.
- With the 'debug' option it just prints the command it would execute and exits.
Uses the 'find' and 'rm' Linux / *NIX / OS X commands, which restricts it to
these platforms.
Note: be careful with this script, it's quite powerful.
"""
import os, sys
def change_to_file_dir():
os.chdir(os.path.abspath(os.path.dirname(__file__)))
def read_clean_patterns():
try:
with open('.gitignore', 'r') as f:
clean_patterns = f.readlines()
except IOError as err:
sys.stderr.write('Could not open .gitignore file: ', err)
sys.exit(2)
return clean_patterns
def create_clean_command(clean_patterns):
clean_patterns = ['-o -name "' + item.replace('\n', '') + '" '
for item in clean_patterns]
first = 0
clean_patterns[first] = clean_patterns[first].replace('-o ', '')
clean_command = str()
for x in clean_patterns:
clean_command += x
if len(sys.argv) > 1 and sys.argv[1] == 'dirs':
clean_command = ('find . \( ' +
clean_command + '\) -exec rm -vrf "{}" \;')
else:
clean_command = ('find . \( ' +
clean_command + '\) -exec rm -vf "{}" \;')
return clean_command
if __name__ == '__main__':
if (len(sys.argv) > 1 and
sys.argv[1] != 'dirs' and
sys.argv[1] != 'debug'):
print('Usage: clean [dirs] [debug]')
print(' dirs: recursive, remove directories too')
print(' debug: only print command, don\'t execute')
sys.exit()
change_to_file_dir()
clean_patterns = read_clean_patterns()
clean_command = create_clean_command(clean_patterns)
if sys.argv[-1] == 'debug':
print ('Clean command is:', clean_command, sep='\n')
else:
os.system(clean_command)
#! /usr/bin/env python3
from tkinter import Tk, Frame, Canvas, Menu, Label, SUNKEN, BOTTOM, W, X
class root_win(Tk):
def __init__(self):
Tk.__init__(self)
def run(self):
self.build_window()
self.mainloop()
def build_window(self):
self.title('My prototype window')
self.build_menu()
self.build_statusbar()
self.resize()
def build_menu(self):
self.menu = Menu()
self.config(menu = self.menu)
self.m_file = Menu(self.menu)
self.m_file.add_command(
label='Quit', command = self.destroy)
self.menu.add_cascade(label='File', menu = self.m_file)
def build_statusbar(self):
self.statusbar = Label(borderwidth=1, relief=SUNKEN, anchor=W)
self.statusbar.config( text = 'Started..')
self.statusbar.pack(fill=X, side=BOTTOM)
def resize(self):
w, h = self.winfo_screenwidth(), self.winfo_screenheight()
self.geometry("%dx%d+0+0" % (w, h))
gui = root_win()
gui.run()