Posted on Leave a comment

How to make an Alarm Clock using Tkinter and Python

To make the python code into an executable. I followed this guide How to make a python script into an executable file.

Python Code

from tkinter import *
from tkinter import ttk
import time

timeVar = time.localtime()
#time.struct_time(tm_year=2022, tm_mon=12, tm_mday=3,
#tm_hour=13, tm_min=3, tm_sec=45, tm_wday=5, tm_yday=337, tm_isdst=0)

#print(timeVar.tm_sec)

root = Tk()

root.title("Time Display")
hourVar = StringVar()
minVar = StringVar()
secVar = StringVar()

Ahour = StringVar()
Amin = StringVar()
Asec = StringVar()
AsetTimeHour = StringVar()
AsetTimeMin = StringVar()
AsetTimeSec = StringVar()

frame = ttk.Frame(root)
frame.grid()

frame11 = ttk.Frame(root, padding = 10)
frame11.grid(column = 1,row=0)

s = ttk.Style()
s.theme_use("alt")

def update():
    global timeVar
        #while(1):
    timeVar = time.localtime()
    hourVar.set(str(timeVar.tm_hour))
    minVar.set(str(timeVar.tm_min))
    #minVar.set(str(59))
    secVar.set(str(timeVar.tm_sec))
    if ( (hourVar.get() == Ahour.get()) and (minVar.get() == Amin.get()) and (secVar.get() == Asec.get()) ):
        alarmWin = Toplevel(root)
        root.bell()
        alarmWin.title("Alarm")
        
        #alarmWin.geometry("200x100")
        s.configure("Aframe.TFrame", background = "cyan")
        Aframe = ttk.Frame(alarmWin, style ="Aframe.TFrame" ,padding = 100)
        #Aframe.configure(background = "cyan")
        Aframe.grid()
        
        ttk.Label(Aframe, text = "Alarm ").grid(column=2,row=0,sticky = (W,E))
        ttk.Button(Aframe, text="QUIT", command = alarmWin.destroy).grid(column=0, row=10)
        #root.update()
        #time.sleep(1)
    root.after(1000,update)
        


def alarmset():
    
    childWin = Toplevel(root)
    childWin.title("Alarm Set")
    frame1 = ttk.Frame(childWin)
    frame1.grid()
    ttk.Label(frame1, text = "Hour").grid(column=2,row=0,ipadx = 20,ipady=10)
    ttk.Entry(frame1,textvariable = AsetTimeHour).grid(column=2,row=1)
    ttk.Label(frame1, text = "Min").grid(column=3,row=0)
    ttk.Entry(frame1,textvariable = AsetTimeMin).grid(column=3,row=1)
    ttk.Label(frame1, text = "Sec").grid(column=4,row=0)
    ttk.Entry(frame1,textvariable = AsetTimeSec).grid(column=4,row=1)
    def Aset():
        try:
            xyz = AsetTimeHour.get()
            Ahour.set(str(int(AsetTimeHour.get())))
        except:
            Ahour.set("")
        try:
            Amin.set(str(int(AsetTimeMin.get())))
        except:
            Amin.set("")
        try:
            Asec.set(str(int(AsetTimeSec.get())))
        except:
            Asec.set("")
        #root1.destroy()
    
    ttk.Button(frame1, text="QUIT", command = childWin.destroy).grid(column=0, row=10)
    ttk.Button(frame1, text="Set", command = Aset).grid(column=1, row=10)
    
def alarmset15sec():
    global timeVar
    #timeVar.tm_min = 58
    x = int((timeVar.tm_sec + 15) if (timeVar.tm_sec + 15) <= 59 else (timeVar.tm_sec + 15)-60 )
    y= 0
    z = 0
    if x < 15:
        y = int((timeVar.tm_min + 1) if (timeVar.tm_min + 1) <= 59 else (timeVar.tm_min + 1)-60 )
        #y = ((int(minVar.get()) + 1) if (int(minVar.get()) + 1) <= 59 else int(minVar.get()) + 1 - 60)
        z = int((timeVar.tm_hour ))
        if y < 1:
            z = int((timeVar.tm_hour + 1) if (timeVar.tm_hour + 1) <= 23 else (timeVar.tm_hour + 15)-24 )
        try:
            Amin.set(str(y))
        except:
            Amin.set("")
        try:
            Asec.set(str(x))
        except:
            Asec.set("")
        try:
            Ahour.set(str(z))
        except:
            Ahour.set("")
            
    if x >= 15:
        y = int((timeVar.tm_min ))
        z = int((timeVar.tm_hour ))
        try:
            Amin.set(str(y))
        except:
            Amin.set("")
        try:
            Asec.set(str(x))
        except:
            Asec.set("")
        try:
            Ahour.set(str(z))
        except:
            Ahour.set("")
   
    
    
    

        
s.configure("timelabel.TLabel", font="Arial 24", padding = 20)
hourLabel = ttk.Label(frame, textvariable = hourVar, style = "timelabel.TLabel")
hourLabel.grid(column=1, row = 1,sticky = (E))
ttk.Label(frame,text = " : ", style = "timelabel.TLabel").grid(column=2,row=1)
minLabel = ttk.Label(frame,textvariable = minVar, style = "timelabel.TLabel")
minLabel.grid(column=3, row = 1,sticky = (E))
ttk.Label(frame,text = " : ", style = "timelabel.TLabel").grid(column=4,row=1)
secLabel = ttk.Label(frame, textvariable = secVar, style = "timelabel.TLabel")
secLabel.grid(column=5, row = 1,sticky = (E))

ttk.Label(frame11, text = "Alarm Time").grid(column=1,row=0)
ttk.Label(frame11, text = "Hour").grid(column=1,row=2)
ttk.Label(frame11, textvariable= Ahour).grid(column=1,row=3)

ttk.Label(frame11,text = " : ").grid(column=2,row=3)

ttk.Label(frame11, text = "Min").grid(column=3,row=2)
ttk.Label(frame11, textvariable= Amin).grid(column=3,row=3)

ttk.Label(frame11,text = " : ").grid(column=4,row=3)

ttk.Label(frame11, text = "Sec").grid(column=5,row=2)
ttk.Label(frame11, textvariable= Asec).grid(column=5,row=3)

ttk.Button(frame, text="Quit", command=root.destroy).grid(column=1, row=10)
ttk.Button(frame, text="Alarm Set", command = alarmset).grid(column=2, row=10)
ttk.Button(frame, text="Alarm Set 15 sec", command = alarmset15sec).grid(column=3, row=10)
update()
root.mainloop()
Posted on Leave a comment

How to make a python script into an executable file

To run a python script. You have to open python in either the command prompt or its IDLE.

We can make use of pyinstaller module. Which will take your script and add all the dependencies and create a standalone executable file which you can use just like any other software.

To install pyinstaller

open your command prompt and execute the following code

pip install pyinstaller

This will install pyinstaller .

After doing it. Browse into your script folder.

pyinstaller --onefile your-python-script.py

If you run the above line it will create a self containing executable file.

You can also have a directory in which all the dependency files are placed along with the executable file.

pyinstaller --onedir your-python-script.py

If you do want to have a console.

pyinstaller --onefile --noconsole your-python-script.py

If you want your executable file to have a custom icon. You can put a icon file in the same directory along with your Python script.

pyinstaller --onefile --noconsole -i "icon.ico" your-python-script.py
Posted on Leave a comment

How to make a calculator in Python using Tkinter module

Python Code

from tkinter import *
from tkinter import ttk
expression = ""
def btn_entry(num):
    global expression
    expression = expression + str(num)
    equation.set(expression)

def exp_eval():
    try:            
        global expression
        expression = str(eval(expression))
        equation.set(expression)
    except ZeroDivisionError:
        print(expression)
        equation.set("Division by Zero Error ")
        expression = ""
        
def exp_clear():
    global expression
    expression = ""
    equation.set(expression)
    
sc = Tk()
sc.title("Calculator")

sc.geometry("480x280")
sc.configure(background ="white")

s = ttk.Style()
print(s.theme_use())
s.theme_use("alt")
#s.theme_use("default")

mainframe = ttk.Frame(sc)

#Resize window
for x in range(10):
    sc.columnconfigure(x,weight=x)
    sc.rowconfigure(x,weight=x)

equation = StringVar()
s.configure("keys.TButton",font="Arial 16")
key_1 = ttk.Button(sc,style = "keys.TButton",width = 10, text="1", command=lambda:btn_entry(1))
key_1.grid(column=0,row=1, sticky =(E))
key_2 = ttk.Button(sc,style = "keys.TButton",width = 10, text="2", command=lambda:btn_entry(2))
key_2.grid(column=1,row=1, sticky =(E))
key_3 = ttk.Button(sc,style = "keys.TButton",width = 10, text="3", command=lambda:btn_entry(3))
key_3.grid(column=2,row=1, sticky =(E))
key_4 = ttk.Button(sc,style = "keys.TButton",width = 10, text="4", command=lambda:btn_entry(4))
key_4.grid(column=0,row=2, sticky =(E))
key_5 = ttk.Button(sc,style = "keys.TButton",width = 10, text="5", command=lambda:btn_entry(5))
key_5.grid(column=1,row=2, sticky =(E))
key_6 = ttk.Button(sc,style = "keys.TButton",width = 10, text="6", command=lambda:btn_entry(6))
key_6.grid(column=2,row=2, sticky =(E))
key_7 = ttk.Button(sc,style = "keys.TButton",width = 10, text="7", command=lambda:btn_entry(7))
key_7.grid(column=0,row=3, sticky =(E))
key_8 = ttk.Button(sc,style = "keys.TButton",width = 10, text="8", command=lambda:btn_entry(8))
key_8.grid(column=1,row=3, sticky =(E))
key_9 = ttk.Button(sc,style = "keys.TButton",width = 10, text="9", command=lambda:btn_entry(9))
key_9.grid(column=2,row=3, sticky =(E))
key_0 = ttk.Button(sc,style = "keys.TButton",width = 10, text="0", command=lambda:btn_entry(0))
key_0.grid(column=1,row=4, sticky =(E))
key_dec = ttk.Button(sc,style = "keys.TButton",width = 10, text=".", command=lambda:btn_entry("."))
key_dec.grid(column=0,row=4, sticky =(E))

key_add = ttk.Button(sc,style = "keys.TButton",width = 10, text="+", command=lambda:btn_entry("+"))
key_add.grid(column=3,row=1, sticky =(N))
key_sub = ttk.Button(sc,style = "keys.TButton",width = 10, text="-", command=lambda:btn_entry("-"))
key_sub.grid(column=3,row=2, sticky =(N))
key_mul = ttk.Button(sc,style = "keys.TButton",width = 10, text="*", command=lambda:btn_entry("*"))
key_mul.grid(column=3,row=3, sticky =(N))
key_div = ttk.Button(sc,style = "keys.TButton",width = 10, text="/", command=lambda:btn_entry("/"))
key_div.grid(column=3,row=4, sticky =(N))

s.configure('equal.TButton',background='light green' ,font="Arial 16", embossed = 1)
key_equal = ttk.Button(sc,style = "equal.TButton", text="=",width = 30, command=lambda:exp_eval())
key_equal.grid(column=1,row=5,columnspan=3, sticky=(W))

s.configure('clear.TButton',background='pink' ,font="Arial 16", embossed = 1)
key_clr = ttk.Button(sc, text="CLEAR", style="clear.TButton",width = 10, command=lambda:exp_clear())
key_clr.grid(column=0,row=5, sticky =(E))

s.configure("display.TLabel",background ='yellow' ,padding =20 ,font = "Arial 24")
exp_display = ttk.Label(sc, textvariable = equation, style = "display.TLabel")
exp_display.grid(column=0,columnspan =3,row = 0,sticky=(S,E))
exp_display.columnconfigure(1,weight = 2)


sc.mainloop()
Posted on Leave a comment

How to make an analog clock using Python Turtle Graphics – 3

Python Code

import turtle
from datetime import datetime

screen1 = turtle.Screen()
screen1.setup(500,500,0,0)
screen1.screensize(480,480, bg="#c0c0c0")
screen1.tracer(0)

don = turtle.Turtle()
#don.speed("fastest")
don.width(1)
don.hideturtle()

def draw_square(startx, starty, length):
    don.penup()
    don.home()
    don.goto(startx, starty)
    don.pendown()
    for side in range(4):
        don.forward(length)
        don.right(90)
    don.penup()

def draw_hand(length,rot):
    don.penup()
    don.home()
    don.pendown();
    don.right(1*rot+90*3)
    don.forward(length)
    don.penup()
    don.home()
    
def print_time(hou,minu,sec):
    don.penup()
    don.goto(-180,-190);
    don.pendown()
    data = str(hou)+" : "+str(minu)+" : "+str(sec)
    don.color("white")
    don.write(data, move = False,align='left', font=('Arial', 16, 'normal'));
    don.penup()

def draw_watchface():
    don.penup()
    for x in range(0,360,30):
        don.home()
        don.color("black")
        don.right(x)
        don.forward(150)
        don.pendown();
        don.forward(20)
        don.penup()
        
    for x in range(0,360,6):
        don.home()
        don.color("black")
        don.width(1)
        don.right(x)
        don.forward(150)
        don.pendown();
        don.forward(10)
        don.penup()
    don.penup()
    
def draw_frame(hou,minu,sec):
    don.goto(-200,200);
    don.pendown()
    draw_square(-200,200,400)
    draw_watchface()
    don.color("blue")
    draw_hand(140,sec*6)  #seconds
    don.color("red");
    don.width(3)
    draw_hand(140,minu*6)  #minutes
    don.color("green");
    don.width(10)
    draw_hand(140,hou*6*5)  #hours
    don.width(2)
    don.penup()
    don.goto(-220,-230);
    don.pendown()
    don.write("exasub.com", move = False,align='left', font=('Arial', 16, 'normal'));
    don.penup()
    print_time(hou,minu,sec)
    #print(str(hou)+" : "+str(minu)+" : "+str(sec))

def draw_time():
    while(1):
        t = datetime.today()
        sekunde = t.second 
        minuten = t.minute 
        houren = t.hour
        
        don.clear()
        draw_frame(houren,minuten,sekunde);
        screen1.update()

    
if __name__ == "__main__":
    draw_time()
    turtle.done()
Posted on Leave a comment

How to make simple graphics in Turtle Graphics – 2

Python Code

from turtle import * 

def frame():
    #setup (width=200, height=200, startx=0, starty=0)
    setup(500,500,0,0);
    screensize(canvwidth = 480, canvheight = 480, bg = "cyan")

def box1(size, angle):
    penup()
    goto(-(size/2),(size/2))
    pendown()
    forward(size)
    right(angle)
    forward(size)
    right(angle)
    forward(size)
    right(angle)
    forward(size)
    penup()

def text():
    goto(-230,-230)
    pendown()
    #turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
    write("exasub.com", False, align="left", font = ('Arial', 16, 'normal'))
    
if __name__ == "__main__":
    frame();
    box1(400,90);
    text();
    mainloop()

Python Code

from turtle import * 

def frame():
    #setup (width=200, height=200, startx=0, starty=0)
    setup(500,500,0,0);
    screensize(canvwidth = 480, canvheight = 480, bg = "cyan")

def box1(size, angle):
    penup()
    goto(-(size/2),(size/2))
    pendown()
    forward(size)
    right(angle)
    forward(size)
    right(angle)
    forward(size)
    right(angle)
    forward(size)
    penup()

def text():
    goto(-230,-230)
    pendown()
    #turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
    write("exasub.com", False, align="left", font = ('Arial', 16, 'normal'))
    penup()

def drawCircle():
    # Draw a circle in Anticlockwise direction
    goto(0,0)
    pendown()
    color("red")
    begin_fill()    # Start Filling the semi-circle
    circle(100,-180,40); # circle(radius, angle, steps)
    end_fill()      # Stop Filling the semi-circle
    penup()
    #Draw a circle in Clockwise Direction
    goto(0,0)
    pendown()
    color("green")
    begin_fill()
    circle(100,360,40)
    end_fill()
    penup()

def drawTriangle():
    home()
    pendown()
    color("grey")
    begin_fill()
    circle(50, 360, 3)
    end_fill()
    penup()

    
if __name__ == "__main__":
    frame();
    box1(400,90);
    text();
    drawCircle();
    drawTriangle()
    #drawCircle();
    mainloop()

Posted on Leave a comment

Python Turtle Graphics Introduction – 1

Turtle is a simple, easy and fun way to learn graphical programming.

It contains very simple commands. By combining together these and similar commands, intricate shapes and pictures can easily be drawn.

You can create simple drawings using the turtle module.

You can also create simple animations.

If you want to learn about the nitty-gritty of Turtle you can read their documentation.
https://docs.python.org/3/library/turtle.html#introduction

You do not have to install anything apart from the python programming language.

You can download the python programming language from
https://www.python.org/downloads/

Posted on Leave a comment

Python – Basic Mathematical Programs

How to perform addition.

# Addend + Addend = Sum
a = 19
b = 15

sum = a + b

print("Total Sum of a and b =",sum)

How to perform subtraction

#Minuend - Subtrahend = Difference

Minuend = 22
Subtrahend = 140

Difference = Minuend - Subtrahend

print("The Difference equals to ",Difference)

How to perform multiplication

# Multiplicand X multiplier = product

Multiplicand = 56
Multiplier = 12

Product = Multiplicand * Multiplier

print("The product of the Multiplicand and mulitplier is ",Product)

How to perform division

# Dividend / Divisor = Quotient (Remainder)

Dividend = 18
Divisor = 5

Quotient = Dividend / Divisor

print("The quotient + reminder = ",Quotient)

How to perform if-else operations

# If-else Python

a = 1
b = 1

if (a < b):
    print("A is Lesser than B")
elif (a ==b):
    print("A is equal to B")
else:
    print("A is Greater than B")

How to perform a while loop operation

# While Loop
# Using While Loop to perform multiplication using Addition

A = 13131313

sum = 0;
counter = 1

while (counter < 11):
    sum = A + sum
    print(A," x ",counter," = ",sum)
    counter = 1 + counter
    
Posted on Leave a comment

Using Blender as a High-Quality Scene Render from FreeCAD 3D STL Models

When you create a parametric model in FreeCAD. The model will look very bland. You can add different colors to your 3d model face and you can even make your model transparent to help view the underneath wireframes.

But when you have to present the work to a more general audience you can’t really show a dull-colored 3D object. You need to have the 3D model in some rendering environment which will add colors, shadows, lights, a camera, etc.

12mm Button CAP in FreeCad

As you can see in the above image it is not very pleasing to look at. It will not look very good on a website or printed in a pamphlet.

So we export the 3d model from the FreeCAD to a .stl file.

That STL file will be imported into the blender software.

There in the blender environment, we can add different lights, cameras, colors, and textures to make it look more pleasing to view and create a nice scene.

As you can see these images are more presentable to a wider audience.

Download Links
Blender from https://www.blender.org/download/
FreeCAD from https://www.freecadweb.org/downloads.php

Posted on Leave a comment

FreeCAD and KiCAD workflow for Product Design

They are two software packages designed by two independent teams. Both of them are free to use.

To create a product you will need an enclosure that will house all the essential components inside it. And this enclosure can be built in FreeCAD.

I am using FreeCAD 0.20.1

There are some Addons that I have installed.

You can install Addon from “Tools > Addon Manager”

  1. KiCad StepUP workbench
  2. Glass
  3. PieMenu
  4. A2Plus (for making assembly from different individual parts)
  5. Fasteners Workbench (Easy to use the preconstructed model of many standard nuts, bolts, screws, washers, etc.)

KiCad StepUP workbench provides an ECAD-MCAD collaboration tool.

From what I learned in FreeCAD you create Sketch that can be exported to KiCad PCB.

The KiCad uses the Sketch created in the FreeCAD as Edge Cuts.

Edge Cuts are the outline of the PCB in which all your components along with all the tracks, via, hole, and other miscellaneous items must reside.

Youtube video from user mathcodeprint

This video demonstrates a basic example.

It is not a perfect collaborating tool. There are other software tools available from big companies but they are not affordable for a budding engineer.

The ECAD/MCAD collabration proccess:

  1. Design your schematic in Kicad.
  2. Assign Footprint and make sure that each footprint have a 3d model assigned to its footprint.
  3. make a pcb and update the component from the schematics.
    place a grid origin. Using the grid origin draw a rectangle in the edge cut layer.
  4. Save the pcb.
  5. After doing the above steps open the PCB in the FreeCAD KiCadStepUp workbench.
  6. Load the PCB into the freecad environment using the
    “ksu PushPull > Load Board” option
  7. Make changes to the sketch and the 3d model.

If you select a 3d model and make changes to its position.

To make changes to the 3d model. You have to select that particular model. And then you have to select the model from the Model view. Right click on the model in the Model view and select Transform.

Three orthogonal arrow will be preseneted to you in three different color.
You can move the model by selecting the conical arrow heads.

You have to push the changes by selecting that model into the kicad pcb.

After you have saved the kicad will automatically adust its footprint automatically.

It is this PUSH PULL method of making the changes to your pcb dimension and component positions.

Posted on Leave a comment

How to generate custom fonts for LCD display

There are various tools to generate font style for LCD display.

  1. Write your own fonts style. But this is will become hectic if you have a larger font size.
  2. Software tool
    1. The Dot Factory by Eran Duchan
    2. GLCD Font Creator

I like “The Dot Factory” font creation tool. It is minimalistic and gets the job done.

Here is the link to the Github page for The Dot Factory https://github.com/pavius/the-dot-factory