Skip to content

Instantly share code, notes, and snippets.

@RaspPiGuy
Last active December 26, 2015 01:59
For my blog: thepiandi.blogspot.com. This becomes the module to be called from my program GraphTemperatureWithGUI.py
#!/usr/bin/python
""" This module supports the GraphTemperatureWithGUI.py with a GUI support
Martin Lyon 10/23/2013"""
from Tkinter import *
import os
import subprocess
from datetime import datetime
import cPickle as pickle
def guiwindow():
def getdirectory():
""" Prepares new directory name based upon year, month,and day like: 2013 07 27. This is added
to the base directory /home/pi/Documents/PythonProjects/TempProbe. We check to see if it exists
and creates it if not. """
basedirectory = '/home/pi/Documents/PythonProjects/TempProbe/TempResults/'
newdirectory = datetime.now().strftime('%Y_%m_%d')
os.chdir(basedirectory)
err = 'error'
while err != '':
directorylist = subprocess.Popen('ls', stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = directorylist.communicate()
filedirectory = basedirectory + newdirectory + '/'
if newdirectory not in out:
os.system('mkdir ' + filedirectory)
return filedirectory
def radio():
breadboardLabel.configure(state=DISABLED)
breadboardText.configure(state=DISABLED)
cableLabel.configure(state=DISABLED)
cableText.configure(state=DISABLED)
if sensorsel.get()==0 or sensorsel.get()==2:
breadboardLabel.configure(state=NORMAL)
breadboardText.configure(state=NORMAL)
if sensorsel.get()==1 or sensorsel.get()==2:
cableLabel.configure(state=NORMAL)
cableText.configure(state=NORMAL)
return
def check_escaped(intext, char):
"""Makes sure that all of the space or colon characters are escaped with the backspace character"""
its_good = True
cnt_chars = intext.count(char)
start_pos = 0
while cnt_chars:
index_char = intext.find(char, start_pos)
if intext[index_char -1] != '\\':
its_good = False
start_pos = index_char + 1
cnt_chars -= 1
return its_good
def removemessage():
badEntry0.grid_remove()
badEntry1.grid_remove()
badEntry2.grid_remove()
badEntry3.grid_remove()
badEntry4.grid_remove()
badEntry5.grid_remove()
badEntry6.grid_remove()
badEntry7.grid_remove()
badEntry8.grid_remove()
def loaddefaults():
removemessage()
sensorsel.set(0)
breadboard.set("Breadboard")
cable.set("Cable")
graphtitle.set("Temperature\ Profile")
graphcomments.set("")
whichcolor.set(0)
graphheight.set(400)
maxmeasurements.set("1")
interval_days.set("0")
interval_hours.set("0")
interval_minutes.set("1")
fileoverwrite.set(0)
filenamebase.set("")
radio()
def proceed():
removemessage()
ok = True
# Check Breadboard Legend for nonescaped colons
if not check_escaped(breadboard.get(), ':'):
badEntry0.grid()
ok = False
# Check Cable Legend for nonescaped colons
if not check_escaped(cable.get(), ':'):
badEntry1.grid()
ok = False
# Check Title for nonescaped spaces
if not check_escaped(graphtitle.get(), ' '):
badEntry2.grid()
ok = False
# Check Comments for nonescaped colons
if not check_escaped(graphcomments.get(), ':'):
badEntry3.grid()
ok = False
# Check Max Measurements. Must be digits and not 0
if not maxmeasurements.get().isdigit():
badEntry4.grid()
ok = False
else:
if int(maxmeasurements.get()) == 0:
badEntry4.grid()
ok = False
# Check Measurement Interval. Must be digits and not 0
if not (interval_days.get().isdigit() and interval_hours.get().isdigit() and interval_minutes.get().isdigit()):
badEntry5.grid()
ok = False
else:
if int(interval_days.get()) + int(interval_hours.get()) + int(interval_minutes.get()) == 0:
badEntry5.grid()
ok = False
# Check that File Name is Alpha Numeric, not "", and Overwrite Status
if filenamebase.get() == '':
badEntry8.grid()
ok = False
return
if not '_' in filenamebase.get():
if not filenamebase.get().isalnum():
badEntry6.grid()
ok = False
return
else:
for i in range(len(filenamebase.get())):
if not filenamebase.get()[i].isalnum() and not filenamebase.get()[i] == '_':
badEntry6.grid()
ok = False
return
if fileoverwrite.get() == 0:
file_name = directoryname.get() + filenamebase.get() + ".txt"
try:
f=open(file_name)
f.close
badEntry7.grid()
ok = False
except:
pass
# If everything is OK we close the window
if ok:
root.destroy()
return
def quitprogram():
quitall.set(True)
root.destroy()
return
#---------------------------------------------------------------------
# Main Script
# Initialize Variables
root = Tk()
root.title('PI Temperature Measurements')
root.geometry('700x400')
picklefile = "/home/pi/Documents/PythonProjects/TempProbe/config.pickle"
sensorsel=IntVar()
breadboard=StringVar()
cable=StringVar()
graphtitle=StringVar()
graphcomments=StringVar()
whichcolor=IntVar()
graphheight=IntVar()
maxmeasurements=StringVar()
interval_days=StringVar()
interval_hours=StringVar()
interval_minutes=StringVar()
fileoverwrite=IntVar()
directoryname=StringVar()
directoryname.set(getdirectory())
filenamebase=StringVar()
quitall=BooleanVar()
quitall.set(False)
try:
f = open(picklefile, "r")
configvars = pickle.load(f)
f.close()
sensorsel.set(configvars[0])
breadboard.set(configvars[1])
cable.set(configvars[2])
graphtitle.set(configvars[3])
graphcomments.set(configvars[4])
whichcolor.set(configvars[5])
graphheight.set(configvars[6])
maxmeasurements.set(configvars[7])
interval_days.set(configvars[8])
interval_hours.set(configvars[9])
interval_minutes.set(configvars[10])
fileoverwrite.set(configvars[11])
filenamebase.set(configvars[12])
except:
loaddefaults()
# Setup All the frames
frame1 = Frame(root)
frame1.grid(row = 0, column = 0, sticky = W)
frame2 = Frame(root)
frame2.grid(row = 1, column = 0, sticky = W)
frame3 = Frame(root)
frame3.grid(row = 2, column = 0, sticky = W)
frame4 = Frame(root)
frame4.grid(row = 3, column = 0, sticky = W)
frame5 = Frame(root)
frame5.grid(row = 4, column = 0, sticky = W)
frame6 = Frame(root)
frame6.grid(row = 5, column = 0, sticky = W)
frame7 = Frame(root)
frame7.grid(row = 6, column = 0, sticky = W)
frame8 = Frame(root)
frame8.grid(row = 7, column = 0, sticky = W)
# Set up the font for labels
labelfont = ('times', 12, 'bold')
# Set up the widgets
# Which sensor radiobutton widget:
whichsensorLabel = Label(frame1, text = ' Sensor Selection: ', font = labelfont)
whichsensorLabel.grid(row = 0, column = 0, pady = 5, sticky = W)
whichsensor0 = Radiobutton(frame1, text = 'Breadboard Sensor', variable = sensorsel, value = 0, command = radio)
whichsensor0.grid(row = 0, column = 1)
whichsensor1 = Radiobutton(frame1, text = 'Cable Sensor', variable = sensorsel, value = 1, command = radio)
whichsensor1.grid(row = 0, column = 2)
whichsensor2 = Radiobutton(frame1, text = 'Both Sensors', variable = sensorsel, value = 2, command = radio)
whichsensor2.grid(row = 0, column = 3)
# Breadboard legend entry widget:
breadboardLabel = Label(frame2, text = ' Breadboard Legend: ', font = labelfont)
breadboardLabel.grid(row = 0, column = 0, columnspan = 2, pady = 5, sticky = W)
breadboardText = Entry(frame2, textvariable = breadboard, width = 40)
breadboardText.grid(row = 0, column = 2, padx = 10, sticky = W)
badEntry0 = Label(frame2, text = 'Escape all colons', fg = 'red')
badEntry0.grid(row = 0, column = 3, sticky = W)
badEntry0.grid_remove()
# Cable legend entry widget:
cableLabel = Label(frame2, text = ' Column Legend: ', font = labelfont)
cableLabel.grid(row = 1, column = 0, columnspan = 2, pady = 5, sticky = W)
cableLabel.configure(state = DISABLED)
cableText = Entry(frame2, textvariable = cable, width = 40)
cableText.grid(row = 1, column = 2, padx = 10, sticky = W)
cableText.configure(state = DISABLED)
badEntry1 = Label(frame2, text = 'Escape all colons', fg = 'red')
badEntry1.grid(row = 1, column = 3, sticky = W)
badEntry1.grid_remove()
# Graph Title entry widget:
graphtitleLabel = Label(frame2, text = ' Graph Title: ', font = labelfont)
graphtitleLabel.grid(row = 2, column = 0, columnspan = 2, pady = 5, sticky = W)
graphtitleText = Entry(frame2, textvariable = graphtitle, width = 40)
graphtitleText.grid(row = 2, column = 2, padx = 10, sticky = W)
badEntry2 = Label(frame2, text = 'Escape spaces', fg = 'red')
badEntry2.grid(row = 2, column = 3, sticky = W)
badEntry2.grid_remove()
# Graph comment entry widget:
graphcommentLabel = Label(frame2, text = ' Graph Comment: ', font = labelfont)
graphcommentLabel.grid(row = 3, column = 0, columnspan = 2, pady = 5, sticky = W)
graphcommentText = Entry(frame2, textvariable = graphcomments, width = 40)
graphcommentText.grid(row = 3, column = 2, padx = 10, sticky = W)
badEntry3 = Label(frame2, text = 'Escape all colons', fg = 'red')
badEntry3.grid(row = 3, column = 3, sticky = W)
badEntry3.grid_remove()
# Background color radiobutton widget:
whichcolorLabel = Label(frame3, text = ' Graph Background Color: ', font = labelfont)
whichcolorLabel.grid(row = 0, column = 0, pady = 5, sticky = W)
whichcolor0 = Radiobutton(frame3, text = 'Black', variable = whichcolor, value = 0)
whichcolor0.grid(row = 0, column = 1)
whichcolor1 = Radiobutton(frame3, text = 'White', variable = whichcolor, value = 1)
whichcolor1.grid(row = 0, column = 2)
whichcolor2 = Radiobutton(frame3, text = 'Both', variable = whichcolor, value = 2)
whichcolor2.grid(row = 0, column = 3)
# Graph height scale widget:
graphHiteLable = Label(frame4, text = ' Height of Graph: ', font = labelfont)
graphHiteLable.grid(row = 0, column = 0, sticky = W)
graphHite = Scale(frame4, orient = HORIZONTAL, from_ = 100, to = 400, variable = graphheight)
graphHite.configure(resolution = 100, length = 200, tickinterval = 100)
graphHite.grid(row = 0, column = 1, pady = 5, sticky = W)
# Maximum measurements entry widget:
maxmeasLabel = Label(frame5, text = ' Number of Measurements: ', font = labelfont)
maxmeasLabel.grid(row = 0, column = 0, pady = 5, sticky = W)
maxmeasText = Entry(frame5, textvariable = maxmeasurements, width = 4, justify = RIGHT)
maxmeasText.grid(row = 0, column = 1, padx = 10)
badEntry4 = Label(frame5, text = 'Non-nteger or less than 1 measurement', fg = 'red')
badEntry4.grid(row = 0, column = 2, sticky = W)
badEntry4.grid_remove()
# Measurement interval entry widgets:
intervalLabel0 = Label(frame6, text = ' Measurement Interval: ', font = labelfont)
intervalLabel0.grid(row = 0, column = 0, pady = 5, sticky = W)
interval_daysText = Entry(frame6, textvariable = interval_days, width = 4, justify = RIGHT)
interval_daysText.grid(row = 0, column = 1)
intervalLabel1 = Label(frame6, text = 'day(s) ', font = labelfont)
intervalLabel1.grid(row = 0, column = 2)
interval_hoursText = Entry(frame6, textvariable = interval_hours, width = 3, justify = RIGHT)
interval_hoursText.grid(row = 0, column = 3)
intervalLabel2 = Label(frame6, text = 'hour(s) ', font = labelfont)
intervalLabel2.grid(row = 0, column = 4)
interval_minutesText = Entry(frame6, textvariable = interval_minutes, width = 3, justify = RIGHT)
interval_minutesText.grid(row = 0, column = 5)
intervalLabel3 = Label(frame6, text = 'minute(s)', font = labelfont)
intervalLabel3.grid(row = 0, column = 6)
badEntry5 = Label(frame6, text = ' A non-nteger or less than 1 minute', fg = 'red')
badEntry5.grid(row = 0, column = 7)
badEntry5.grid_remove()
# Check for file overwrite check widget:
filecheckLabel = Label(frame7, text = ' Allow File Overwrite: ', font = labelfont)
filecheckLabel.grid(row = 0, column = 0, pady = 5, sticky = W)
filecheckBox = Checkbutton(frame7, variable = fileoverwrite)
filecheckBox.grid(row = 0, column = 1)
# File name entry widget
filenameLabel = Label(frame7, text = ' Base Filename: ', font = labelfont)
filenameLabel.grid(row = 0, column = 2)
filenameText = Entry(frame7, textvariable = filenamebase, width = 15)
filenameText.grid(row = 0, column = 3)
badEntry6 = Label(frame7, text = ' Only numbers, letters, and underscore', fg = 'red')
badEntry6.grid(row = 0, column = 4)
badEntry6.grid_remove()
badEntry7 = Label(frame7, text = ' Will overwrite existing file', fg = 'red')
badEntry7.grid(row = 0, column = 4)
badEntry7.grid_remove()
badEntry8 = Label(frame7, text = ' Must enter a file name', fg = 'red')
badEntry8.grid(row = 0, column = 4)
badEntry8.grid_remove()
# Continue button widget:
proceedButton = Button(frame8, text = "Continue", command = proceed, font = labelfont, bg = 'green')
proceedButton.configure(activebackground = 'green', width = 8, height = 2)
proceedButton.grid(row = 0, column = 1, padx = 70, pady = 10)
# Quit button widget:
quitButton = Button(frame8, text = 'Quit', command = quitprogram, font = labelfont, bg = 'red')
quitButton.configure(activebackground = 'red', width = 8)
quitButton.grid(row = 0, column = 0, padx = 70)
# Load defaults widget:
defaultsButton = Button(frame8, text = 'Defaults', command = loaddefaults, font = labelfont, bg = 'yellow')
defaultsButton.configure(activebackground = 'yellow', width = 8)
defaultsButton.grid(row = 0, column = 2, padx = 70)
radio()
root.mainloop()
hours = int(interval_hours.get()) + 24 * int(interval_days.get())
minutes = int(interval_minutes.get()) + 60 * hours
total_interval = minutes * 60
passout = []
passout.append(sensorsel.get())
passout.append(breadboard.get())
passout.append(cable.get())
passout.append(graphtitle.get())
passout.append(graphcomments.get())
passout.append(whichcolor.get())
passout.append(graphheight.get())
passout.append(maxmeasurements.get())
passout.append(total_interval)
passout.append(directoryname.get() + filenamebase.get())
passout.append(quitall.get())
configout = []
configout.append(sensorsel.get())
configout.append(breadboard.get())
configout.append(cable.get())
configout.append(graphtitle.get())
configout.append(graphcomments.get())
configout.append(whichcolor.get())
configout.append(graphheight.get())
configout.append(maxmeasurements.get())
configout.append(interval_days.get())
configout.append(interval_hours.get())
configout.append(interval_minutes.get())
configout.append(fileoverwrite.get())
configout.append(filenamebase.get())
try:
f = open(picklefile, "w")
pickle.dump(configout, f)
f.close()
except(IOError):
pass
return passout
#---------------------------------------------------------------------
# Test Code
if __name__ == '__main__':
from time import sleep
try:
variable_list = guiwindow()
if variable_list[10]:
raise(KeyboardInterrupt)
sensor = variable_list[0]
measure_what0 = variable_list[1]
measure_what1 = variable_list[2]
title_it = variable_list[3]
comment = variable_list[4]
background = variable_list[5]
how_high = variable_list[6]
max_measurements = variable_list[7]
measurement_interval = variable_list[8]
filename = variable_list[9]
print "\nsensor: ", sensor
print "breadboard legend: ", measure_what0
print "cable legend: ", measure_what1
print "graph title: ", title_it
print "comment: ", comment
print "background color: ", background
print "graph height: ", how_high
print "maximum number of measurements: ", max_measurements
print "measurement interval: ", measurement_interval
print "base file name: ", filename
# Create keyboard interrupt to test last line of code
print "\nHit CTRL C"
sleep(100)
except(KeyboardInterrupt):
if not variable_list[10]:
print "\nStuff at end of program"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment