Showing posts with label Project. Show all posts
Showing posts with label Project. Show all posts

Photo Sideshow

import tkinter as tk

from tkinter import *

from PIL import Image

from PIL import ImageTk

root=tk.Tk()

root.geometry("200x200")

img=ImageTk.PhotoImage(Image.open("photo1.png"))

img2=ImageTk.PhotoImage(Image.open("photo2.png"))

img3=ImageTk.PhotoImage(Image.open("photo3.png"))

l=Label()

l.pack()

x = 1

def move():

    global x

    if x == 4:

        x = 1

    if x == 1:

        l.config(image=img)

    elif x == 2:

        l.config(image=img2)

    elif x == 3:

        l.config(image=img3)

    x = x+1

    root.after(2000, move)

move()

root.mainloop()


memory game

from random import *

from turtle import *

screen = Screen()

screen.bgcolor("yellow")

def Square(x, y):

    up()

    goto(x, y)

    down()

    color('white', 'red')

    begin_fill()

    for count in range(4):

        forward(50)

        left(90)

    end_fill()

def numbers(x, y):

    return int((x + 200) // 50 + ((y + 200) // 50) * 8)

def Coordinates(count):

    return (count % 8) * 50 - 200, (count // 8) * 50 - 200

def click(x, y):

    spot = numbers(x, y)

    mark = state['mark']

    if mark is None or mark == spot or tiles[mark] != tiles[spot]:

        state['mark'] = spot

    else:

        hide[spot] = False

        hide[mark] = False

        state['mark'] = None

def draw():

    clear()

    goto(0, 0)

    stamp()

    for count in range(64):

        if hide[count]:

            x, y = Coordinates(count)

            Square(x, y)

    mark = state['mark']

    if mark is not None and hide[mark]:

        x, y = Coordinates(mark)

        up()

        goto(x + 2, y)

        color('white')

        write(tiles[mark], font=('Arial', 30, 'normal'))

    update()

    ontimer(draw, 10)

tiles = list(range(32)) * 2

state = {'mark': None}

hide = [True] * 64

shuffle(tiles)

tracer(False)

onscreenclick(click)

draw()

done()


Background remover app

import tkinter as tk

from rembg import remove

from PIL import Image

from tkinter import filedialog

from PIL import Image

import os

from tkinter import messagebox

top = tk.Tk()

top.geometry("400x400")

top.title('Background Remover')

filename = ''

def upload_file():

    global filename

    f_types = [('Jpg Files', '*.jpg')]

    filename = filedialog.askopenfilename(filetypes=f_types)

    if len(filename) > 0:

        b1.config(state='disabled')

def Convert(image_name):

    current_working_directory = os.getcwd()

    input_path = filename

    output_path = f'{current_working_directory}\{image_name}.png'

    image_input = Image.open(input_path)

    output = remove(image_input)

    output.save(output_path)

    messagebox.showinfo('Success', 'Image background successfully removed')

    top.destroy()

my_font1 = ('times', 18, 'bold')

l1 = tk.Label(top, text='Background Removal App', width=30, font=my_font1)

l1.grid(row=1, column=1)

b1 = tk.Button(top, text='Select here', height=2, font=('Arial', 20), bg='green', fg='white', command=lambda: upload_file())

b1.grid(row=2, column=1, pady=20)

image_name = tk.StringVar(top)

image_name.set('enter file name')

e1 = tk.Entry(top, textvariable=image_name)

e1.grid(row=3, column=1, pady=20)

b2 = tk.Button(top, text='Convert now', height=2, font=('Arial', 20), bg='green', fg='white', command=lambda: Convert(image_name.get()))

b2.grid(row=4, column=1, pady=20)

top.mainloop()

File Explorer

from tkinter import *

from tkinter import filedialog

def browseFiles():

    filename = filedialog.askopenfilename(initialdir = "/",

                                        title = "Select a File",

                                        filetypes = (("Text files",

                                                        "*.txt*"),

                                                    ("all files",

                                                        "*.*")))

    label_file_explorer.configure(text="File Opened: "+filename)                                                                                              

window = Tk()

window.title('File Explorer')

window.geometry("500x500")

window.config(background = "white")

label_file_explorer = Label(window,

                            text = "File Explorer using Tkinter",

                            width = 100, height = 4,

                            fg = "blue")

button_explore = Button(window,

                        text = "Browse Files",

                        command = browseFiles)

button_exit = Button(window,

                    text = "Exit",

                    command = exit)

label_file_explorer.grid(column = 1, row = 1)

button_explore.grid(column = 1, row = 2)

button_exit.grid(column = 1,row = 3)

window.mainloop()


Screenshot using pyscreenshot

The simplest way of taking a screenshot using pyscreenshot module

Install the package:

               pip install pyscreenshot 


import pyscreenshot

image = pyscreenshot.grab()

image.show()

image.save("screenshot.png")


Flames Checker

def rmv_match_char(list1, list2):

    for i in range(len(list1)):

        for j in range(len(list2)):

            if list1[i] == list2[j]:

                c = list1[i]

                list1.remove(c)

                list2.remove(c)

                list3 = list1 + ["*"] + list2

                return [list3, True]

    list3 = list1 + ["*"] + list2

    return [list3, False]

if __name__ == "__main__":

    p1 = input("Player 1 name : ")

    p1 = p1.lower()

    p1.replace(" ", "")

    p1_list = list(p1)

    p2 = input("Player 2 name : ")

    p2 = p2.lower()

    p2.replace(" ", "")

    p2_list = list(p2)

    proceed = True

    while proceed:

        ret_list = rmv_match_char(p1_list, p2_list)

        con_list = ret_list[0]

        proceed = ret_list[1]

        star_index = con_list.index("*")

        p1_list = con_list[: star_index]

        p2_list = con_list[star_index + 1:]

    count = len(p1_list) + len(p2_list)

    result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"]

    while len(result) > 1:

        split_index = (count % len(result) - 1)

        if split_index >= 0:

            right = result[split_index + 1:]

            left = result[: split_index]

            result = right + left

        else:

            result = result[: len(result) - 1]

    print("Relationship status :", result[0])


Olympic Symbol

import turtle

tr = turtle.Turtle()

tr.pensize(5)

tr.color("blue")

tr.penup()

tr.goto(-110, -25)

tr.pendown()

tr.circle(45)

tr.color("black")

tr.penup()

tr.goto(0, -25)

tr.pendown()

tr.circle(45)

tr.color("red")

tr.penup()

tr.goto(110, -25)

tr.pendown()

tr.circle(45)

tr.color("yellow")

tr.penup()

tr.goto(-55, -75)

tr.pendown()

tr.circle(45)

tr.color("green")

tr.penup()

tr.goto(55, -75)

tr.pendown()

tr.circle(45)


Page Switching

import tkinter as tk

from tkinter import ttk

LARGEFONT =("Verdana", 35)

class switchApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)

        container.pack(side = "top", fill = "both", expand = True)

        container.grid_rowconfigure(0, weight = 1)

        container.grid_columnconfigure(0, weight = 1)

        self.frames = {}

        for F in (StartPage, Page1, Page2):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row = 0, column = 0, sticky ="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]

        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text ="Startpage", font = LARGEFONT)

        label.grid(row = 0, column = 4, padx = 10, pady = 10)

        button1 = ttk.Button(self, text ="Page 1",

        command = lambda : controller.show_frame(Page1))

        button1.grid(row = 1, column = 1, padx = 10, pady = 10)

        button2 = ttk.Button(self, text ="Page 2",

        command = lambda : controller.show_frame(Page2))

        button2.grid(row = 2, column = 1, padx = 10, pady = 10)

class Page1(tk.Frame): 

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text ="Page 1", font = LARGEFONT)

        label.grid(row = 0, column = 4, padx = 10, pady = 10)

        button1 = ttk.Button(self, text ="StartPage",

                            command = lambda : controller.show_frame(StartPage))

        button1.grid(row = 1, column = 1, padx = 10, pady = 10)

        button2 = ttk.Button(self, text ="Page 2",

                            command = lambda : controller.show_frame(Page2))

        button2.grid(row = 2, column = 1, padx = 10, pady = 10)

class Page2(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = ttk.Label(self, text ="Page 2", font = LARGEFONT)

        label.grid(row = 0, column = 4, padx = 10, pady = 10)

        button1 = ttk.Button(self, text ="Page 1",

                            command = lambda : controller.show_frame(Page1))

        button1.grid(row = 1, column = 1, padx = 10, pady = 10)

        button2 = ttk.Button(self, text ="Startpage",

                            command = lambda : controller.show_frame(StartPage))

        button2.grid(row = 2, column = 1, padx = 10, pady = 10)

app = switchApp()

app.mainloop()


EMI calculator

from tkinter import *

class EmiCalculator:

    def __init__(self):

        window = Tk() 

        window.title("Loan Calculator") 

        Label(window, text = "Annual Interest Rate").grid(row = 1,

                                        column = 1, sticky = W)

        Label(window, text = "Number of Years").grid(row = 2,

                                    column = 1, sticky = W)

        Label(window, text = "Loan Amount").grid(row = 3,

                                column = 1, sticky = W)

        Label(window, text = "Monthly Payment").grid(row = 4,

                                    column = 1, sticky = W)

        Label(window, text = "Total Payment").grid(row = 5,

                                    column = 1, sticky = W)

        self.annualInterestRateVar = StringVar()

        Entry(window, textvariable = self.annualInterestRateVar,

                    justify = RIGHT).grid(row = 1, column = 2)

        self.numberOfYearsVar = StringVar()

        Entry(window, textvariable = self.numberOfYearsVar,

                justify = RIGHT).grid(row = 2, column = 2)

        self.loanAmountVar = StringVar()

        Entry(window, textvariable = self.loanAmountVar,

            justify = RIGHT).grid(row = 3, column = 2)

        self.monthlyPaymentVar = StringVar()

        lblMonthlyPayment = Label(window, textvariable =

                        self.monthlyPaymentVar).grid(row = 4,

                        column = 2, sticky = E)

        self.totalPaymentVar = StringVar()

        lblTotalPayment = Label(window, textvariable =

                    self.totalPaymentVar).grid(row = 5,

                    column = 2, sticky = E)

        btComputePayment = Button(window, text = "Compute Payment",

                                command = self.computePayment).grid(

                                row = 6, column = 2, sticky = E)

        window.mainloop() 

    def computePayment(self):

        monthlyPayment = self.getMonthlyPayment(

        float(self.loanAmountVar.get()),

        float(self.annualInterestRateVar.get()) / 1200,

        int(self.numberOfYearsVar.get()))

        self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))

        totalPayment = float(self.monthlyPaymentVar.get()) * 12 \

                                * int(self.numberOfYearsVar.get())

        self.totalPaymentVar.set(format(totalPayment, '10.2f'))

    def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):

        monthlyPayment = loanAmount * monthlyInterestRate / (1

        - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))

        return monthlyPayment;

        root = Tk() 

EmiCalculator()



Bubble sort visualizer

import pygame

pygame.init()

win = pygame.display.set_mode((500, 400))

pygame.display.set_caption("Bubble sort")

x = 40

y = 40

width = 20

height = [200, 50, 130, 90, 250, 61, 110,

            88, 33, 80, 70, 159, 180, 20]

run = True

def show(height):

    for i in range(len(height)):

        pygame.draw.rect(win, (255, 0, 0), (x + 30 * i, y, width, height[i]))

while run:

    execute = False

    pygame.time.delay(10)

    keys = pygame.key.get_pressed()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            run = False

    if keys[pygame.K_SPACE]:

        execute = True

    if execute == False:

        win.fill((0, 0, 0))

        show(height)

        pygame.display.update()

    else:

        for i in range(len(height) - 1):

            for j in range(len(height) - i - 1):

                if height[j] > height[j + 1]:

                    t = height[j]

                    height[j] = height[j + 1]

                    height[j + 1] = t

                win.fill((0, 0, 0))

                show(height)

                pygame.time.delay(50)

                pygame.display.update()

pygame.quit()


Age Calculator

from tkinter import *

from tkinter import messagebox

def clearAll() :

    dayField.delete(0, END)

    monthField.delete(0, END)

    yearField.delete(0, END)

    givenDayField.delete(0, END)

    givenMonthField.delete(0, END)

    givenYearField.delete(0, END)

    rsltDayField.delete(0, END)

    rsltMonthField.delete(0, END)

    rsltYearField.delete(0, END)

def checkError() :

    if (dayField.get() == "" or monthField.get() == ""

        or yearField.get() == "" or givenDayField.get() == ""

        or givenMonthField.get() == "" or givenYearField.get() == "") :

        messagebox.showerror("Input Error")

        clearAll()

        return -1

def calculateAge() :

    value = checkError()

    if value == -1 :

        return

    else :

        birth_day = int(dayField.get())

        birth_month = int(monthField.get())

        birth_year = int(yearField.get())

        given_day = int(givenDayField.get())

        given_month = int(givenMonthField.get())

        given_year = int(givenYearField.get())

        month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        if (birth_day > given_day):

            given_month = given_month - 1

            given_day = given_day + month[birth_month-1]

        if (birth_month > given_month):

            given_year = given_year - 1

            given_month = given_month + 12

        calculated_day = given_day - birth_day;

        calculated_month = given_month - birth_month;

        calculated_year = given_year - birth_year;

        rsltDayField.insert(10, str(calculated_day))

        rsltMonthField.insert(10, str(calculated_month))

        rsltYearField.insert(10, str(calculated_year))

if __name__ == "__main__" :

    gui = Tk()

    gui.configure(background = "light green")

    gui.title("Age Calculator")

    gui.geometry("525x260")

    dob = Label(gui, text = "Date Of Birth", bg = "light green")

    givenDate = Label(gui, text = "Given Date", bg = "light green")

    day = Label(gui, text = "Day", bg = "light green")

    month = Label(gui, text = "Month", bg = "light green")

    year = Label(gui, text = "Year", bg = "light green")

    givenDay = Label(gui, text = "Given Day", bg = "light green")

    givenMonth = Label(gui, text = "Given Month", bg = "light green")

    givenYear = Label(gui, text = "Given Year", bg = "light green")

    rsltYear = Label(gui, text = "Years", bg = "light green")

    rsltMonth = Label(gui, text = "Months", bg = "light green")

    rsltDay = Label(gui, text = "Days", bg = "light green")

    resultantAge = Button(gui, text = "Resultant Age", fg = "Black", bg = "light blue", command = calculateAge)

    clearAllEntry = Button(gui, text = "Clear All", fg = "Black", bg = "light blue", command = clearAll)

    dayField = Entry(gui)

    monthField = Entry(gui)

    yearField = Entry(gui)

    givenDayField = Entry(gui)

    givenMonthField = Entry(gui)

    givenYearField = Entry(gui)

    rsltYearField = Entry(gui)

    rsltMonthField = Entry(gui)

    rsltDayField = Entry(gui)

    dob.grid(row = 0, column = 1)

    day.grid(row = 1, column = 0)

    dayField.grid(row = 1, column = 1)

    month.grid(row = 2, column = 0)

    monthField.grid(row = 2, column = 1)

    year.grid(row = 3, column = 0)

    yearField.grid(row = 3, column = 1)

    givenDate.grid(row = 0, column = 4)

    givenDay.grid(row = 1, column = 3)

    givenDayField.grid(row = 1, column = 4)

    givenMonth.grid(row = 2, column = 3)

    givenMonthField.grid(row = 2, column = 4)

    givenYear.grid(row = 3, column = 3)

    givenYearField.grid(row = 3, column = 4)

    resultantAge.grid(row = 4, column = 2)

    rsltYear.grid(row = 5, column = 2)

    rsltYearField.grid(row = 6, column = 2)

    rsltMonth.grid(row = 7, column = 2)

    rsltMonthField.grid(row = 8, column = 2)

    rsltDay.grid(row = 9, column = 2)

    rsltDayField.grid(row = 10, column = 2)

    clearAllEntry.grid(row = 12, column = 2)

    gui.mainloop()


Image Viewer

from tkinter import *

from PIL import ImageTk, Image

def forward(img_no):

    global label

    global button_forward

    global button_back

    global button_exit

    label.grid_forget()

    label = Label(image=List_images[img_no-1])

    label.grid(row=1, column=0, columnspan=3)

    button_for = Button(root, text="forward",

                        command=lambda: forward(img_no+1))

    if img_no == 4:

        button_forward = Button(root, text="Forward",

                                state=DISABLED)

    button_back = Button(root, text="Back",

                        command=lambda: back(img_no-1))

    button_back.grid(row=5, column=0)

    button_exit.grid(row=5, column=1)

    button_for.grid(row=5, column=2)

def back(img_no):

    global label

    global button_forward

    global button_back

    global button_exit

    label.grid_forget()

    label = Label(image=List_images[img_no - 1])

    label.grid(row=1, column=0, columnspan=3)

    button_forward = Button(root, text="forward",

                            command=lambda: forward(img_no + 1))

    button_back = Button(root, text="Back",

                        command=lambda: back(img_no - 1))

    print(img_no)

    if img_no == 1:

        button_back = Button(root, Text="Back", state=DISABLED)

    label.grid(row=1, column=0, columnspan=3)

    button_back.grid(row=5, column=0)

    button_exit.grid(row=5, column=1)

    button_for.grid(row=5, column=2)

root = Tk()

root.title("Image Viewer")

root.geometry("700x700")

image_no_1 = ImageTk.PhotoImage(Image.open("sample.jpg"))

image_no_2 = ImageTk.PhotoImage(Image.open("sample.jpg"))

image_no_3 = ImageTk.PhotoImage(Image.open("sample.jpg"))

image_no_4 = ImageTk.PhotoImage(Image.open("sample.jpg"))

List_images = [image_no_1, image_no_2, image_no_3, image_no_4]

label = Label(image=image_no_1)

label.grid(row=1, column=0, columnspan=3)

button_back = Button(root, text="Back", command=back,

                    state=DISABLED)

button_exit = Button(root, text="Exit",

                    command=root.quit)

button_forward = Button(root, text="Forward",

                        command=lambda: forward(1))

button_back.grid(row=5, column=0)

button_exit.grid(row=5, column=1)

button_forward.grid(row=5, column=2)

root.mainloop()


Voice Recorder

import sounddevice as sd

from scipy.io.wavfile import write

import wavio as wv

freq = 44100

duration = 5

recording = sd.rec(int(duration * freq),

                samplerate=freq, channels=2)

sd.wait()

write("recording0.wav", freq, recording)

wv.write("recording1.wav", recording, freq, sampwidth=2)


Percentage Finder

from tkinter import *

def getPercentage() :

    students= int(total_participantField.get())

    rank = int(rankField.get())

    result = round((students - rank) / students * 100,3);

    percentageField.insert(10, str(result))

def Clear():

    rankField.delete(0, END)

    total_participantField.delete(0, END)

    percentageField.delete(0, END)

if __name__ == "__main__" :

    gui = Tk()

    gui.configure(background = "light pink")

    gui.title("Rank Based- percentage Calculator")

    gui.geometry("650x200")

    rank = Label(gui, text = "Rank", bg = "light green")

    andl = Label(gui, text = "And", bg = "light green")

    total_participant = Label(gui,

                            text = "Total Participants",

                            bg = "light green")

    find = Button(gui, text = "Find percentage",

                fg = "Black", bg = "Red",

                command = getPercentage)

    percentage = Label(gui, text = "percentage", bg = "light green")

    clear = Button(gui, text = "Clear",

                fg = "Black", bg = "Red",

                command = Clear)

    rank.grid(row = 1, column = 1,padx = 10)

    andl.grid(row = 1, column = 4)

    total_participant.grid(row = 1, column = 6, padx = 10)

    find.grid(row = 3, column = 4,pady = 10)

    percentage.grid(row = 4, column = 3,padx = 10)

    clear.grid(row = 5, column = 4,pady = 10)

    rankField = Entry(gui)

    total_participantField = Entry(gui)

    percentageField = Entry(gui)

    rankField.grid(row = 1, column = 2)

    total_participantField.grid(row = 1, column = 7)

    percentageField.grid(row = 4, column = 4)

    

    gui.mainloop()


Tree using python turtle

from turtle import *

speed('fastest')

# turning the turtle to face upwards

rt(-90)

# the base and branch of the Y

angle = 30

# function to plot a Y

def y(sz, level):

    if level > 0:

        colormode(255)

        pencolor(0, 255//level, 0)

        fd(sz)

        rt(angle)

        # recursive call 

        y(0.8 * sz, level-1)

        pencolor(0, 255//level, 0)

        lt( 2 * angle )

        y(0.8 * sz, level-1)

        pencolor(0, 255//level, 0)

        rt(angle)

        fd(-sz)

y(80, 7)


Sentiment Analyzer

from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

from tkinter import *

def clear() :

    negativeField.delete(0, END)

    neutralField.delete(0, END)

    positiveField.delete(0, END)

    overallField.delete(0, END)

    textArea.delete(1.0, END)

def detect_sentiment():

    sentence = textArea.get("1.0", "end")

    sid_obj = SentimentIntensityAnalyzer()

    sentiment_dict = sid_obj.polarity_scores(sentence)

    string = str(sentiment_dict['neg']*100) + "% Negative"

    negativeField.insert(10, string)

    string = str(sentiment_dict['neu']*100) + "% Neutral"

    neutralField.insert(10, string)

    string = str(sentiment_dict['pos']*100) +"% Positive"

    positiveField.insert(10, string)

    if sentiment_dict['compound'] >= 0.05 :

        string = "Positive"

    elif sentiment_dict['compound'] <= - 0.05 :

        string = "Negative"

    else :

        string = "Neutral"

    overallField.insert(10, string)

if __name__ == "__main__" :

    gui = Tk()

    gui.config(background = "light blue")

    gui.title("Sentiment Detector")

    gui.geometry("250x400")

    enterText = Label(gui, text = "Enter Your Sentence",

                                    bg = "light blue")

    textArea = Text(gui, height = 5, width = 25, font = "lucida 13")

    check = Button(gui, text = "Check Sentiment", fg = "Black",

                        bg = "Red", command = detect_sentiment)

    negative = Label(gui, text = "sentence was rated as: ",

                                        bg = "light blue")

    neutral = Label(gui, text = "sentence was rated as: ",

                                    bg = "light blue")

    positive = Label(gui, text = "sentence was rated as: ",

                                        bg = "light blue")

    overall = Label(gui, text = "Sentence Overall Rated As: ",

                                        bg = "light blue")

    negativeField = Entry(gui)

    neutralField = Entry(gui)

    positiveField = Entry(gui)

    overallField = Entry(gui)

    clear = Button(gui, text = "Clear", fg = "Black",

                    bg = "Red", command = clear)

    Exit = Button(gui, text = "Exit", fg = "Black",

                        bg = "Red", command = exit)

    enterText.grid(row = 0, column = 2)

    textArea.grid(row = 1, column = 2, padx = 10, sticky = W)

    check.grid(row = 2, column = 2)

    negative.grid(row = 3, column = 2)

    neutral.grid(row = 5, column = 2)

    positive.grid(row = 7, column = 2)

    overall.grid(row = 9, column = 2)

    negativeField.grid(row = 4, column = 2)

    neutralField.grid(row = 6, column = 2)             

    positiveField.grid(row = 8, column = 2)

    overallField.grid(row = 10, column = 2)

    clear.grid(row = 11, column = 2)

    Exit.grid(row = 12, column = 2)

    gui.mainloop()

    


Racing Animation

from turtle import * 

from random import randint

speed(0)

penup()

goto(-140, 140)

for step in range(15):

write(step, align ='center')

right(90)

for num in range(8):

penup()

forward(10)

pendown()

forward(10)

penup()

backward(160)

left(90)

forward(20)

player_1 = Turtle()

player_1.color('red')

player_1.shape('turtle')

player_1.penup()

player_1.goto(-160, 100)

player_1.pendown()

for turn in range(10):

player_1.right(36)

player_2 = Turtle()

player_2.color('blue')

player_2.shape('turtle')

player_2.penup()

player_2.goto(-160, 70)

player_2.pendown()

for turn in range(72):

player_2.left(5)

player_3 = Turtle()

player_3.shape('turtle')

player_3.color('green')

player_3.penup()

player_3.goto(-160, 40)

player_3.pendown()

for turn in range(60):

player_3.right(6)

player_4 = Turtle()

player_4.shape('turtle')

player_4.color('orange')

player_4.penup()

player_4.goto(-160, 10)

player_4.pendown()

for turn in range(30):

player_4.left(12)

for turn in range(100):

player_1.forward(randint(1, 5))

player_2.forward(randint(1, 5))

player_3.forward(randint(1, 5))

player_4.forward(randint(1, 5))


BGR color palette

import cv2

import numpy as np

def emptyFunction():

pass

def main():

image = np.zeros((512, 512, 3), np.uint8)

windowName ="Open CV Color Palette"

cv2.namedWindow(windowName)

cv2.createTrackbar('Blue', windowName, 0, 255, emptyFunction)

cv2.createTrackbar('Green', windowName, 0, 255, emptyFunction)

cv2.createTrackbar('Red', windowName, 0, 255, emptyFunction)

while(True):

cv2.imshow(windowName, image)

if cv2.waitKey(1) == 27:

break

blue = cv2.getTrackbarPos('Blue', windowName)

green = cv2.getTrackbarPos('Green', windowName)

red = cv2.getTrackbarPos('Red', windowName)

image[:] = [blue, green, red]

print(blue, green, red)

cv2.destroyAllWindows()

if __name__=="__main__":

main()


Countdown Timer

import time

from tkinter import *

from tkinter import messagebox

root = Tk()

root.geometry("300x250")

root.title("Time Counter")

hour=StringVar()

minute=StringVar()

second=StringVar()

hour.set("00")

minute.set("00")

second.set("00")

hourEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=hour)

hourEntry.place(x=80,y=20)


minuteEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=minute)

minuteEntry.place(x=130,y=20)


secondEntry= Entry(root, width=3, font=("Arial",18,""),

textvariable=second)

secondEntry.place(x=180,y=20)

def submit():

try:

temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get())

except:

print("Please input the right value")

while temp >-1:

mins,secs = divmod(temp,60)

hours=0

if mins >60:

hours, mins = divmod(mins, 60)

hour.set("{0:2d}".format(hours))

minute.set("{0:2d}".format(mins))

second.set("{0:2d}".format(secs))

root.update()

time.sleep(1)

if (temp == 0):

messagebox.showinfo("Time Countdown", "Time's up ")

temp -= 1

btn = Button(root, text='Set Time Countdown', bd='5',

command= submit)

btn.place(x = 70,y = 120)

root.mainloop()


Pedestrian Detector for images

import cv2

import imutils

# detector

hog = cv2.HOGDescriptor()

hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# Reading the Image

image = cv2.imread('img_path')

# Resizing the Image

image = imutils.resize(image,

width=min(400, image.shape[1]))

# Detecting all the regions in the

# Image that has a pedestrians inside it

(regions, _) = hog.detectMultiScale(image,

winStride=(4, 4),

padding=(4, 4),

scale=1.05)

# Drawing the regions in the Image

for (x, y, w, h) in regions:

cv2.rectangle(image, (x, y),

(x + w, y + h),

(0, 0, 255), 2)

# Showing the output Image

cv2.imshow("Image", image)

cv2.waitKey(0)

cv2.destroyAllWindows()