I am launching rails server using rails -v 4.2.0 with the following code...
"rails server -b $IP -p $port" and getting the following error.
/usr/local/rvm/gems/ruby-2.1.5#rails4/gems/railties-4.2.0/lib/rails/commands/server.rb:12:in `parse!': missing argument: -p (OptionParser::MissingArgument)
Can someone please explain the missing argument and how to fix it?
Thks
Try rails s -b $IP -p $PORT. Case is important. Bonus for you - you can use s as a shortcut for server.
I get the haarcascade_frontalface_deflult.xml file from cPanel the file are present there but it cannot detect the face its working locally fine but when I upload it on cPanel it did not detect faces properly
face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml')
i also try this
cv2.CascadeClassifier('http://theangrynerds.com/media/haarcascade_frontalface_default.xml')
you can check file http://www.theangrynerds.com/media/haarcascade_frontalface_default.xml
my complete module code here
#login_required(login_url='login')
def imgDelete(request,id):
# if request.method== 'POST':
Image.objects.filter(name=id).delete()
FaceName.objects.filter(name = id).delete()
allimages = FaceName.objects.filter(User=request.user)
# for p in allPdf:
# print("http://127.0.0.1:8000/"+p.thumbnail)
context={
'allimg' : allimages
}
return render(request, 'Application/imagess.html',context)
def location(request):
return render(request, 'Application/location.html')
def out(request):
logout(request)
return redirect('login')
def hello(request):
if request.method == "POST":
F_name = request.POST['name']
user_video = request.FILES['vide']
videoSave = videoStore.objects.create(User=User.objects.get(id=request.user.pk) , videoFile = user_video)
get_path_video = videoStore.objects.get(pk = videoSave.pk)
accurate_path = "http://theangrynerds.com/media/" + str(get_path_video.videoFile)
faceCount = FaceName.objects.all().count()
face_id = faceCount + 1
count =0
video = cv2.VideoCapture(accurate_path)
# Detect object in video stream using Haarcascade Frontal Face
face_detector = cv2.CascadeClassifier('/home/khblpkn3ru9o/public_html/media/haarcascade_frontalface_default.xml')
while True:
# Capture video frame
cc, image_frame = video.read()
if cc == False:
break
# Convert frame to grayscale
gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY)
# Detect frames of different sizes, list of faces rectangles
faces = face_detector.detectMultiScale(gray, 1.3, 5)
# Loops for each faces
for (x,y,w,h) in faces:
# Crop the image frame into rectangle
FaceName.objects.create(User=User.objects.get(id=request.user.pk) , name = F_name , ids = face_id)
# cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2)
count += 1
has = cv2.imwrite("/home/khblpkn3ru9o/public_html/media/" + str(request.user.username) + "." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
c = str(request.user.username)+"." + str(face_id) + '.' + str(count) + ".jpg"
Image.objects.create(User=User.objects.get(id=request.user.pk), name=F_name , imagestore= c )
if count == 100:
break
FaceName.objects.create(User=User.objects.get(id=request.user.pk) , name = F_name , ids = face_id)
video.release()
return redirect('imagess')
Related
I have images in the same directory as the python file named like below.
- cat.png
- dog.png
- turtle.png
- flower.png
Currently I can run a program one at a time like below
os.system('picol.py cat.png -s -d')
Output:
colors_cat.png (with color palettes inside the image)
But I want to do the same thing for all the images in the directory without having to type image names one by one in the shell command.If I have 100+ images in the folder, I would have to type all 100 image names one by one which is ridiculous. It would be convenient if I can just double click on the py file (below attached) and run everything at once.
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
import colorgram
import argparse
from PIL import Image, ImageDraw, ImageFont
import os
from glob import glob
# The font directory is one level higher than this file.
FONT_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'fonts'
)
def get_font(fontname, size):
try:
font_object = ImageFont.truetype(
os.path.join(FONT_DIR, fontname),
size
)
return font_object
except(OSError):
print('Couldn\'t find font \'{}\''.format(fontname))
print('Searched {}'.format(FONT_DIR))
sys.exit()
def rgb_to_hex(value1, value2, value3):
"""
Convert RGB color to hex color
"""
for value in (value1, value2, value3):
if not 0 <= value <= 255:
raise ValueError('Value each slider must be ranges from 0 to 255')
return {'hex_color': '#{0:02X}{1:02X}{2:02X}'.format(value1, value2,
value3), 'link': 'http://www.color-hex.com/color/{0:02X}{1:02X}'
'{2:02X}'.format(value1, value2, value3)}
def get_center_position_hor(canvas_height, image_in_h):
"""
Get the correct position for an image to center it horizontally
"""
if image_in_h < canvas_height:
_canvas_mid = int(canvas_height / 2)
_image_in_mid = int(image_in_h / 2)
return _canvas_mid - _image_in_mid
else:
return 0
def get_center_position_ver(canvas_width, canvas_height, image_h_in):
"""
Get the correct position for an image to center it vertically
"""
_canvas_mid = int(canvas_height / 2)
_image_in_mid = int(image_h_in / 2)
return _canvas_mid - _image_in_mid
def write_out(out, filename):
"""
Write 'out' to 'filename'
"""
with open(filename, 'w') as fout:
fout.write(out)
def main():
parser = argparse.ArgumentParser()
parser.prog = 'piccol'
parser.description = 'Extract the ten most used colors in an image.'
parser.add_argument('image', action='store')
parser.add_argument('-s', '--save-image', help='Save image to a given file',
action='store_true', dest='save_image')
parser.add_argument('-d', '--do-not-show', help='Do not show the image that '
'is made', action='store_false', dest='do_not_show_image')
parser.add_argument('-st', '--save-text', help='Save text to a given file',
action='store_true', dest='save_text')
args = parser.parse_args()
# Get filename of input file
_file_name = args.image.split('/')
file_name = _file_name[len(_file_name) - 1]
# Extract colors from an image.
colors = colorgram.extract(args.image, 10)
# Make a smaller version of the received image
image_in = Image.open(args.image)
image_in.thumbnail((500, 500))
image_in_w, image_in_h = image_in.size
# Set height for canvas. This is dynamic, but has no effect until one can
# increase/decrease the number of colors to output
canvas_height = int(len(colors)) * 50
# ...but if the canvas height is smaller than image_in height, set canvas
# height to image_in height
if canvas_height < image_in_h:
canvas_height = image_in_h
# Testing shows that 750px wide should be enough
canvas_width = 750
img = Image.new('RGB', (canvas_width, canvas_height), 'white')
# Paste image_in into canvas and find out center position
center_hor = get_center_position_hor(canvas_height, image_in_h)
img.paste(image_in, (0, center_hor))
out = ImageDraw.Draw(img)
# Get fonts
title_fnt = get_font('OpenSans-Light.ttf', 30)
hex_fnt = get_font('OpenSans-LightItalic.ttf', 24)
# Write header
title_w, title_h = title_fnt.getsize(file_name)
center_ver = get_center_position_ver(canvas_width, canvas_height, title_w)
out.text((center_ver, 7), file_name, font=title_fnt, fill=(0, 0, 0))
write_output = 'Colors for \'{}\':'.format(file_name)
hor = 0
ver = 120
i = 0
for color in colors:
color_out = rgb_to_hex(color.rgb.r, color.rgb.g, color.rgb.b)
if i == 0:
pass
else:
hor += 50
ver += 50
# rectangle(())
out.rectangle((550, hor, 600, ver), fill=color_out['hex_color'])
out.text((610, 7 + hor), color_out['hex_color'], font=hex_fnt,
fill=(0, 0, 0))
i += 1
if args.save_text:
write_output += '\n{} - {}'.format(color_out['hex_color'],
color_out['link'])
out_file_name = file_name.split('.')[0]
out_file_name = 'colors_{}'.format(out_file_name)
if args.save_text:
out_file_name += '.txt'
write_out(write_output, out_file_name)
if args.save_image:
out_file_name += '.jpg'
img.save(out_file_name)
if args.do_not_show_image is not False:
img.show()
if __name__ == '__main__':
main()
Save the following code as bulk_upload.py in the same folder and call it like this os.system('bulk_upload.py *.png -s -d')
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
import colorgram
import argparse
from PIL import Image, ImageDraw, ImageFont
import os
import glob
# The font directory is one level higher than this file.
FONT_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'fonts'
)
def get_font(fontname, size):
try:
font_object = ImageFont.truetype(
os.path.join(FONT_DIR, fontname),
size
)
return font_object
except(OSError):
print('Couldn\'t find font \'{}\''.format(fontname))
print('Searched {}'.format(FONT_DIR))
sys.exit()
def rgb_to_hex(value1, value2, value3):
"""
Convert RGB color to hex color
"""
for value in (value1, value2, value3):
if not 0 <= value <= 255:
raise ValueError('Value each slider must be ranges from 0 to 255')
return {'hex_color': '#{0:02X}{1:02X}{2:02X}'.format(value1, value2,
value3), 'link': 'http://www.color-hex.com/color/{0:02X}{1:02X}'
'{2:02X}'.format(value1, value2, value3)}
def get_center_position_hor(canvas_height, image_in_h):
"""
Get the correct position for an image to center it horizontally
"""
if image_in_h < canvas_height:
_canvas_mid = int(canvas_height / 2)
_image_in_mid = int(image_in_h / 2)
return _canvas_mid - _image_in_mid
else:
return 0
def get_center_position_ver(canvas_width, canvas_height, image_h_in):
"""
Get the correct position for an image to center it vertically
"""
_canvas_mid = int(canvas_height / 2)
_image_in_mid = int(image_h_in / 2)
return _canvas_mid - _image_in_mid
def write_out(out, filename):
"""
Write 'out' to 'filename'
"""
with open(filename, 'w') as fout:
fout.write(out)
parser = argparse.ArgumentParser()
parser.prog = 'piccol'
parser.description = 'Extract the ten most used colors in an image.'
parser.add_argument('image', action='store')
parser.add_argument('-s', '--save-image', help='Save image to a given file',
action='store_true', dest='save_image')
parser.add_argument('-d', '--do-not-show', help='Do not show the image that '
'is made', action='store_false', dest='do_not_show_image')
parser.add_argument('-st', '--save-text', help='Save text to a given file',
action='store_true', dest='save_text')
args = parser.parse_args()
def process_image(image_path):
"""
Process each image
"""
# Get filename of input file
_file_name = image_path.split('/')
file_name = _file_name[len(_file_name) - 1]
# Extract colors from an image.
colors = colorgram.extract(image_path, 10)
# Make a smaller version of the received image
image_in = Image.open(image_path)
image_in.thumbnail((500, 500))
image_in_w, image_in_h = image_in.size
# Set height for canvas. This is dynamic, but has no effect until one can
# increase/decrease the number of colors to output
canvas_height = int(len(colors)) * 50
# ...but if the canvas height is smaller than image_in height, set canvas
# height to image_in height
if canvas_height < image_in_h:
canvas_height = image_in_h
# Testing shows that 750px wide should be enough
canvas_width = 750
img = Image.new('RGB', (canvas_width, canvas_height), 'white')
# Paste image_in into canvas and find out center position
center_hor = get_center_position_hor(canvas_height, image_in_h)
img.paste(image_in, (0, center_hor))
out = ImageDraw.Draw(img)
# Get fonts
title_fnt = get_font('OpenSans-Light.ttf', 30)
hex_fnt = get_font('OpenSans-LightItalic.ttf', 24)
# Write header
title_w, title_h = title_fnt.getsize(file_name)
center_ver = get_center_position_ver(canvas_width, canvas_height, title_w)
out.text((center_ver, 7), file_name, font=title_fnt, fill=(0, 0, 0))
write_output = 'Colors for \'{}\':'.format(file_name)
hor = 0
ver = 120
i = 0
for color in colors:
color_out = rgb_to_hex(color.rgb.r, color.rgb.g, color.rgb.b)
if i == 0:
pass
else:
hor += 50
ver += 50
# rectangle(())
out.rectangle((550, hor, 600, ver), fill=color_out['hex_color'])
out.text((610, 7 + hor), color_out['hex_color'], font=hex_fnt,
fill=(0, 0, 0))
i += 1
if args.save_text:
write_output += '\n{} - {}'.format(color_out['hex_color'],
color_out['link'])
out_file_name = file_name.split('.')[0]
out_file_name = 'colors_{}'.format(out_file_name)
if args.save_text:
out_file_name += '.txt'
write_out(write_output, out_file_name)
if args.save_image:
out_file_name += '.jpg'
img.save(out_file_name)
if args.do_not_show_image is not False:
img.show()
def main():
# Allowed extensions for bulk processing
allowed_exts = ['*.png','*.jpg']
for i in allowed_exts:
if str(args.image).lower().endswith(i):
for j in sorted(glob.glob(i)):
file_path = os.path.join(os.path.dirname(args.image),j)
print(file_path)
process_image(file_path)
break
else:
process_image(args.image)
if __name__ == '__main__':
main()
P.S. I do not take the responsibility for any type of system break/failure
I have a list of images to make a collage named in a certain pattern.
Ex.
yahoo_jp.png
yahoo_us.png
yahoo_uk.png
yahoo_cn.png
All files are in the same directory. Currently, I can only send a command to make a collage out of all images in a folder but what I want to do is to be able to send a certain keyword from the shell command and look up a list of files in the folder with the keywords matching and then making a collage.
Ex. shell command
make_collage.py -o my_collage.png -w 540 -i 840 new argument --> -a "_us"
- when this command is run, it will only make a collage with files containing keyword "_us" only. So the output would be a collage containing only the "_us" images.
import argparse
import os
import random
from PIL import Image
def make_collage(images, filename, width, init_height):
"""
Make a collage image with a width equal to `width` from `images` and save to `filename`.
"""
if not images:
print('No images for collage found!')
return False
margin_size = 2
# run until a suitable arrangement of images is found
while True:
# copy images to images_list
images_list = images[:]
coefs_lines = []
images_line = []
x = 0
while images_list:
# get first image and resize to `init_height`
img_path = images_list.pop(0)
img = Image.open(img_path)
img.thumbnail((width, init_height))
# when `x` will go beyond the `width`, start the next line
if x > width:
coefs_lines.append((float(x) / width, images_line))
images_line = []
x = 0
x += img.size[0] + margin_size
images_line.append(img_path)
# finally add the last line with images
coefs_lines.append((float(x) / width, images_line))
# compact the lines, by reducing the `init_height`, if any with one or less images
if len(coefs_lines) <= 1:
break
if any(map(lambda c: len(c[1]) <= 1, coefs_lines)):
# reduce `init_height`
init_height -= 10
else:
break
# get output height
out_height = 0
for coef, imgs_line in coefs_lines:
if imgs_line:
out_height += int(init_height / coef) + margin_size
if not out_height:
print('Height of collage could not be 0!')
return False
collage_image = Image.new('RGB', (width, int(out_height)), (35, 35, 35))
# put images to the collage
y = 0
for coef, imgs_line in coefs_lines:
if imgs_line:
x = 0
for img_path in imgs_line:
img = Image.open(img_path)
# if need to enlarge an image - use `resize`, otherwise use `thumbnail`, it's faster
k = (init_height / coef) / img.size[1]
if k > 1:
img = img.resize((int(img.size[0] * k), int(img.size[1] * k)), Image.ANTIALIAS)
else:
img.thumbnail((int(width / coef), int(init_height / coef)), Image.ANTIALIAS)
if collage_image:
collage_image.paste(img, (int(x), int(y)))
x += img.size[0] + margin_size
y += int(init_height / coef) + margin_size
collage_image.save(filename)
return True
def main():
# prepare argument parser
parse = argparse.ArgumentParser(description='Photo collage maker')
parse.add_argument('-f', '--folder', dest='folder', help='folder with images (*.jpg, *.jpeg, *.png)', default='.')
parse.add_argument('-o', '--output', dest='output', help='output collage image filename', default='collage.png')
parse.add_argument('-w', '--width', dest='width', type=int, help='resulting collage image width')
parse.add_argument('-i', '--init_height', dest='init_height', type=int, help='initial height for resize the images')
parse.add_argument('-s', '--shuffle', action='store_true', dest='shuffle', help='enable images shuffle')
args = parse.parse_args()
if not args.width or not args.init_height:
parse.print_help()
exit(1)
# get images
files = [os.path.join(args.folder, fn) for fn in os.listdir(args.folder)]
images = [fn for fn in files if os.path.splitext(fn)[1].lower() in ('.jpg', '.jpeg', '.png')]
if not images:
print('No images for making collage! Please select other directory with images!')
exit(1)
# shuffle images if needed
if args.shuffle:
random.shuffle(images)
print('Making collage...')
res = make_collage(images, args.output, args.width, args.init_height)
if not res:
print('Failed to create collage!')
exit(1)
print('Collage is ready!')
if __name__ == '__main__':
main()
The easiest way would be to use glob.glob() along with os.listdir(), although glob() uses bash syntax so you'll need to enter *_us*.
First import it:
from glob import glob
Then add a "pattern" optional positional arg:
parse.add_argument('-p', '--pattern', nargs="?", default=None, help="enter a grep-like expansion.")
Finally, change the line under # get images to something like this:
if args.pattern:
files = [fn for fn in glob(os.path.join(args.folder, args.pattern))]
else:
files = [os.path.join(args.folder, fn) for fn in os.listdir(args.folder)]
How to send there arguments in #register.filter(name='thumbnail') template tag. I am using image resize function have contain 2 args image object and size now i want to pass third argument folder_name but i can't able to find the solution its gives error Could not parse the remainder: below are function which is template tag file and template.
Template Tag function
#register.filter(name='thumbnail')
def thumbnail(file, size='200x200',folder_name='users_images'):
x, y = [int(x) for x in size.split('x')]
# defining the filename and the miniature filename
filehead, filetail = os.path.split(file.path)
basename, format = os.path.splitext(filetail)
miniature = basename + '_' + size + format
#filename = file.path
#print(filehead+'/users_images/'+filetail)
if os.path.exists(filehead+'/'+folder_name+'/'+filetail):
filename = filehead+'/'+folder_name+'/'+filetail
filehead = filehead+'/'+folder_name+'/'
else:
filename = file.path
#print(filename)
miniature_filename = os.path.join(filehead, miniature)
filehead, filetail = os.path.split(file.url)
miniature_url = filehead + '/' + miniature
if os.path.exists(
miniature_filename
) and os.path.getmtime(filename) > os.path.getmtime(
miniature_filename
):
os.unlink(miniature_filename)
# if the image wasn't already resized, resize it
if not os.path.exists(miniature_filename):
image = Image.open(filename)
new_image = image.resize([x, y], Image.ANTIALIAS)
# image.thumbnail([x, y], Image.ANTIALIAS)
try:
# image.save(miniature_filename, image.format, quality=90, optimize=1)
new_image.save(miniature_filename, image.format,
quality=95, optimize=1)
except:
return miniature_url
return miniature_url
Template File
I have tried 2 different type
{{ contact_list.picture|thumbnail:'200x200' 'contacts'}}
{{ contact_list.picture|thumbnail:'200x200','contacts'}}
If any one have solution please help me.
Thanks
In django, template filter does not accept multiple arguments. So you can try like this:
#register.filter(name='thumbnail')
def thumbnail(file, args):
_params = args.split(',')
if len(_params) == 1:
size = _params[0]
folder_name = "default_folder"
elif len(_params) == 2:
size = _params[0]
folder_name = _params[1]
else:
raise Error
x, y = [int(x) for x in size.split('x')]
...
usage:
{{ contact_list.picture|thumbnail:'200x200,contacts'}}
Please check this SO answer for more details.
hey guys:)im sorry for all the code but i feel its necessary for u to see everything..
i tried everything... i hidden prints in the code, debugging for ten times, triple checked the built in methods, and still, the .crawl() method dosnt remove any object from the final_list.
the object of my assignment is to built two classes:
Web_page : holds data of a web page.(the pages come in the form of html files saved in a folder on my desktop. Crawler: compare between pages and hold a list of the uniqe pages---> final_list
import re
import os
def remove_html_tags(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
quote = not quote
elif not tag:
out = out + c
return out
def lev(s1, s2):
return lev_iter(s1, s2, dict())
def lev_iter(s1, s2, mem):
(i,j) = (len(s1), len(s2))
if (i,j) in mem:
return mem[(i,j)]
s1_low = s1.lower()
s2_low = s2.lower()
if len(s1_low) == 0 or len(s2_low) == 0:
return max(len(s1_low), len(s2_low))
d1 = lev_iter(s1_low[:-1], s2_low, mem) + 1
d2 = lev_iter(s1_low, s2_low[:-1], mem) + 1
last = 0 if s1_low[-1] == s2_low[-1] else 1
d3 = lev_iter(s1_low[:-1], s2_low[:-1], mem) + last
result = min(d1, d2, d3)
mem[(i,j)] = result
return result
def merge_spaces(content):
return re.sub('\s+', ' ', content).strip()
""" A Class that holds data on a Web page """
class WebPage:
def __init__(self, filename):
self.filename = filename
def process(self):
f = open(self.filename,'r')
LINE_lst = f.readlines()
self.info = {}
for i in range(len(LINE_lst)):
LINE_lst[i] = LINE_lst[i].strip(' \n\t')
LINE_lst[i] = remove_html_tags(LINE_lst[i])
lines = LINE_lst[:]
for line in lines:
if len(line) == 0:
LINE_lst.remove(line)
self.body = ' '.join(LINE_lst[1:])
self.title = LINE_lst[0]
f.close()
def __str__(self):
return self.title + '\n' + self.body
def __repr__(self):
return self.title
def __eq__(self,other):
n = lev(self.body,other.body)
k = len(self.body)
m = len(other.body)
return float(n)/max(k,m) <= 0.15
def __lt__(self,other):
return self.title < other.title
""" A Class that crawls the web """
class Crawler:
def __init__(self, directory):
self.folder = directory
def crawl(self):
pages = [f for f in os.listdir(self.folder) if f.endswith('.html')]
final_list = []
for i in range(len(pages)):
pages[i] = WebPage(self.folder + '\\' + pages[i])
pages[i].process()
for k in range(len(final_list)+1):
if k == len(final_list):
final_list.append(pages[i])
elif pages[i] == final_list[k]:
if pages[i] < final_list[k]:
final_list.append(pages[i])
final_list.remove(final_list[k])
break
print final_list
self.pages = final_list
everything works fine besides this freaking line final_list.remove(final_list[k]). help please? whats wrong here?
I'm not sure why your code doesn't work, it's difficult to test it because I don't know what kind of input should end up calling remove().
I suggest following these steps:
Make sure that remove() is called at some point.
remove() relies on your __eq__() method to find the item to remove, so make sure that __eq__() isn't the culprit.
As a side note, you will probably want to replace this:
self.folder + '\\' + pages[i]
with:
import os.path
# ...
os.path.join(self.folder, page[i])
This simple change should make your script work on all operating systems, rather than on Windows only. (GNU/Linux, Mac OS and other Unix-like OS use “/” as path separator.)
Please also consider replacing loops of this form:
for i in range(len(sequence)):
# Do something with sequence[i]
with:
for item in sequence:
# Do something with item
If you need the item index, use enumerate():
for i, item in enumerate(sequence):
I trying to create physics calculator using python tkinter but I find it quite difficult. I have done this calculator in Command line interface but I a bit different with tkinter. basically, I have 5 entry boxes and above each one of them a button. the user will insert values in three of them and should press the button on top of each unknown value to make the calculation and get the result. my main issue is how can I create a function that evaluates the inputs in my entry boxes and make the calculation then print the results inside the entry box. I made some coding but unfortunately the operation is not working due to few mistakes.
here is my coding part:
from Tkinter import *
import math
class calculator():
def is_positive_number(number): # validation function
if number <= 0:
return False
else :
return True
def value_of_time(prompt):
while True: # loop command for time
try:
valid = False
while not valid:
value = float((prompt))
if is_positive_number(value):
valid = True
return value
else :
valid = False
print ('I donot know what is happening')
except ValueError:
print("Oops, unfortunately this is a wrong input, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
def input_of_box(prompt):
while True: # loop for initial velocity
try:
value = float(input(prompt))
return value
except ValueError:
print("Oops, we are you not typing a number, please try again.")
#better try again... Return to the start of the loop
continue
else:
#value was successfully parsed!
#we're ready to exit the loop.
break
# def minput(numberofinput):
if numberofinput == 1:
t = value_of_time("Enter the time that takes an object to accelerate in seconds:")
return
elif numberofinput == 2:
u = input_of_box("Enter the initial velocity in m/s:")
return
elif numberofinput == 2:
v = input_of_box("Enter the final velocity in m/s:")
return
def my_calculation(mvariables): # this function is to operate the calculation
if mvariables == 1:
a = (v-u) /(t)
mentery1 = a
return
elif mvariables == 2:
v = u + a*t
mentery2 = v
return
elif mvariables == 3:
u = a*t - v
mentery3 = t
elif mvariables == 4:
t = (v - u)/a
mentery3 = t
return
elif mvariables == 5:
s = (v**2-u**2)/2*a
mentery4 = s
else:
print ('there is an error')
cal = Tk()
cal.configure(background='sky blue')
a = StringVar()
u = StringVar()
v = StringVar()
t = StringVar()
s = StringVar()
cal.geometry('650x420+350+225')
cal.title('Main Menu')
# here we start greating buttons and entry boxes
m_label = Label(text='Calculator',fg = 'Navy', font=("Helvetica", 20,"bold italic"), bg='sky blue')
m_label.pack()
button1 = Button(cal,text='A',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(1))
button1.place(x=92,y=210)
mentery1 = Entry(cal, textvariable = a ,width=10,bd =3)
mentery1.place(x=82,y=240)
button2 = Button(cal,text='U',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(3))
button2.place(x=192,y=210)
mentery2 = Entry(cal, textvariable = u ,width=10,bd =3)
mentery2.place(x=182,y=240)
button3 = Button(cal,text='V',fg='white',bg='dark green',bd =3, width=4, command= lambda : my_calculation(2))
button3.place(x=292,y=210)
mentery3 = Entry(cal, textvariable = v ,width=10,bd =3)
mentery3.place(x=282,y=240)
button4 = Button(cal,text='T',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(4))
button4.place(x=392,y=210)
mentery4 = Entry(cal, textvariable = t ,width=10,bd =3)
mentery4.place(x=382,y=240)
button5 = Button(cal,text='S',fg='white',bg='dark green',bd =3, width=4,command= lambda : my_calculation(5))
button5.place(x=492,y=210)
mentery5 = Entry(cal, textvariable = s , width=10,bd =3)
mentery5.place(x=482,y=240)
# end of button commands
app = calculator()
app.mainloop()
For validating the input, do the following:
def returnValidatedInput(entry):
value = entry.get() # Get the text in the 'entry' widget
evaluation = eval(value) # Evaluate 'value'
return evaluation
And for inserting the answers into the entries (it's not called printing the answers into the entries):
def insertAnswer(entry, answer):
entry.delete(0, 'end') # Be sure the entry is empty, if it is not, clear it
entry.insert(END, str(answer)) # Insert the answer into the 'entry' widget.