Saturday, December 26, 2020

Rock Paper Scissors in Tkinter

 







RPS.png is 446 x 446
Other 3 images are 58 x 46


from tkinter import *

from random import randint

import time


win = Tk()

win.title("ROCK - PAPER - SCISSORS")

win.geometry("800x560+120+0")

win.configure(bg='black')


def Rock():

  pic = PhotoImage(file="Rock.gif")

  CChoice = randint(1, 3)

  if CChoice == 1:

    lblResult.config(text="Both chose Rock - Draw", bg="black", fg="white")

  elif CChoice == 2:

    lblResult.config(text="Computer's Paper covers Your Rock - Computer Wins", bg="red", fg="white")

    I1.set(I1.get() + 1)

  else:

    lblResult.config(text="Your Rock smashes Computer's Scissors - You Win", bg="green", fg="white")

    I2.set(I2.get() + 1)

      

def Paper():

  pic = PhotoImage(file="Paper.gif")

  CChoice = randint(1, 3)

  if CChoice == 1:

    lblResult.config(text="Your Paper covers Computer's Rock - You Win", bg="green", fg="white")

    I2.set(I2.get() + 1)

  elif CChoice == 2:

    lblResult.config(text="Both chose Paper - Draw", bg="black", fg="white")

  else:

    lblResult.config(text="Computer's Scissors cuts Your Paper - Computer Wins", bg="red", fg="white")

    I1.set(I1.get() + 1)

    

def Scissors():

  pic = PhotoImage(file="Scissors.gif")

  CChoice = randint(1, 3)

  if CChoice == 1:

    lblResult.config(text="Computer's Rock smashes Your Scissors - Computer Wins", bg="red", fg="white")

    I1.set(I1.get() + 1)

  elif CChoice == 2:

    lblResult.config(text="Your Scissors cuts Computer's Paper - You Win", bg="green", fg="white")

    I2.set(I2.get() + 1)

  else:

    lblResult.config(text="Both chose Scissors - Draw", bg="black", fg="white")


pic1 = PhotoImage(file="RPS.gif")

lblMain = Label(win, image=pic1, bg="black");  lblMain.place(x=185, y=0)


I1, I2 = IntVar(), IntVar()

lblCompScore1 = Label(win, text="Computer score", bg="black", fg="white", font=("Helvetica", 16, "bold"))

lblCompScore1.place(x=20, y=30)

lblCompScore2 = Label(win, textvariable=I1, bg="black", fg="white", font=("Helvetica", 16, "bold"))

lblCompScore2.place(x=100, y=70)

lblPlayerScore1 = Label(win, text="Player score", bg="black", fg="white", font=("Helvetica", 16, "bold"))

lblPlayerScore1.place(x=630, y=30)

lblPlayerScore2 = Label(win, textvariable=I2, bg="black", fg="white", font=("Helvetica", 16, "bold"))

lblPlayerScore2.place(x=690, y=70)


lblResult = Label(win, bg="white", width=44, font=("Helvetica", 16, "bold"), text="Hello")

lblResult.place(x=120, y=460)


pic2     = PhotoImage(file="Rock.gif")

rock     = Button(win, image=pic2, bg="black", command=Rock)

rock.place(x=300, y=500)

pic3     = PhotoImage(file="Paper.gif")

paper    = Button(win, image=pic3, bg="black", command=Paper)

paper.place(x=380, y=500)

pic4     = PhotoImage(file="Scissors.gif")

scissors = Button(win, image=pic4, bg="black", command=Scissors)

scissors.place(x=450, y=500)


win.mainloop()


Thursday, December 10, 2020

Generating ASCII Art from image using Python


   

# https://dev.to/anuragrana/generating-ascii-art-from-colored-image-using-python-4ace

import sys

from PIL import Image


image_path = "Thejus1.png"

img = Image.open(image_path)


width, height = img.size

aspect_ratio = height/width

new_width = 120

new_height = aspect_ratio * new_width * 0.55

img = img.resize((new_width, int(new_height)))

img = img.convert('L')


pixels = img.getdata()


chars = ["B","S","#","&","@","$","%","*","!",":"," "]

new_pixels = [chars[pixel//25] for pixel in pixels]

new_pixels = ''.join(new_pixels)


new_pixels_count = len(new_pixels)

ascii_image = [new_pixels[index:index + new_width] for index in range(0, new_pixels_count, new_width)]

ascii_image = "\n".join(ascii_image)

print(ascii_image)


with open("ThejusASCII.txt", "w") as f:

  f.write(ascii_image)


Friday, December 4, 2020

Grayscale & Dither in Python

 


#https://www.youtube.com/watch?v=3RVnDX8cO4s&list=PL1H1sBF1VAKXCayO4KZqSmym2Z_sn6Pha&index=5


from tkinter import *

from PIL import ImageTk, Image


win = Tk()

win.title("Converting images")

win.geometry("600x510+50+50")


file1 = "..\\Images\\Originals\\Elephant.png"

img1 = Image.open(file1)


def Select(e):

  global select

  selected = lbox.curselection()

  select = lbox.get(selected)


  img = Image.open("..\\Images\\Originals\\Elephant.png")

  if select == "Normal":

    imgConv = img.convert(None)

  elif select == "Grayscale":

    imgConv = img.convert("L")

  elif select == "Dither":

    imgConv = img.convert("1")


  imgConv.save("..\\Images\\Modified\\ElephantConvert.png")

  pic = PhotoImage(file="..\\Images\\Modified\\ElephantConvert.png")

  lbl1.config(image=pic)

  lbl1.image = pic


pic = PhotoImage(file=file1)

lbl1 = Label(win, image=pic)

lbl1.place(x=30, y=60)

lbl1.image = pic


lbox = Listbox(win, height=3, font=("Arial", 11))

lbox.insert(1, "Normal")

lbox.insert(2, "Grayscale")

lbox.insert(3, "Dither")

lbox.place(x=215, y=410)

lbox.bind('<<ListboxSelect>>', Select)


win.mainloop()



Blend images with PIL in Python


# https://www.youtube.com/watch?v=7IdBppdM23Y&list=PL1H1sBF1VAKXCayO4KZqSmym2Z_sn6Pha&index=3

# Before loading files, ensure images to be blended have same dimensions


from tkinter import *

from PIL import ImageTk, Image


win = Tk()

win.title("Blending images")

win.geometry("720x700")


file1 = "..\\Images\\Amazon.png"

file2 = "..\\Images\\Elephant.png"


def Save(e):

  img1 = Image.open(file1)

  img2 = Image.open(file2)

  imgBlend = Image.blend(img1, img2, D.get()/100)

  imgBlend.save('..\\Images\\Blended.png')

  pic = PhotoImage(file='..\\Images\\Blended.png')

  lblBlend.config(image=pic)

  lblBlend.image = pic

  del img1, img2

  

D = DoubleVar()

scl1 = Scale(win, variable=D, from_=0, to=100, orient=HORIZONTAL, length=600, sliderlength=10)

scl1.bind("<Motion>", Save)

scl1.place(x=30, y=10)


openImage1 = Image.open("..\\Images\\Amazon.png")

openImage1.thumbnail((300, 300))

img1 = ImageTk.PhotoImage(openImage1)

lbl1 = Label(win, image=img1)

lbl1.place(x=30, y=60)


openImage2 = Image.open("..\\Images\\Elephant.png")

openImage2.thumbnail((300, 300))

img2 = ImageTk.PhotoImage(openImage2)

lbl2 = Label(win, image=img2)

lbl2.place(x=375, y=60)


openImage2 = Image.open("..\\Images\\Amazon.png")

imgStart = ImageTk.PhotoImage(openImage2)

lblBlend = Label(win, image=imgStart)

lblBlend.place(x=75, y=260)


Thursday, December 3, 2020

Blur Types (Simple, Box, Gaussian) in PIL using Tkinter


from tkinter import *

from PIL import ImageTk, ImageFilter, Image


win = Tk()

win.title("Blur Image")

win.geometry("600x600")


D = IntVar()


def Blur(type):

  d = D.get()     # Convert Tkinter variable to object

  oriImage = Image.open('..\\Images\\Boy.png')

  if type == "Simple":

    blurImage = oriImage.filter(ImageFilter.BLUR)

  elif type == "Box":

    blurImage = oriImage.filter(ImageFilter.BoxBlur(d))

  elif type == "Gaussian":

    blurImage = oriImage.filter(ImageFilter.GaussianBlur(d))


  blurImage.save('..\\Images\\BoyBlur.png')

  pic1 = PhotoImage(file="..\\Images\\BoyBlur.png")

  lbl.config(image=pic1)

  lbl.image = pic1


scl1 = Scale(win, variable=D, from_=0, to=20, orient=HORIZONTAL)

scl1.place(x=30, y=10)


btnSimpleBlur   = Button(win, text="Simple Blur",   command=lambda:Blur("Simple"))

btnSimpleBlur.place(x=50, y=500)

btnBoxBlur      = Button(win, text="Box Blur",      command=lambda:Blur("Box"))

btnBoxBlur.place(x=150, y=500)

btnGaussianBlur = Button(win, text="Gaussian Blur", command=lambda:Blur("Gaussian"))

btnGaussianBlur.place(x=250, y=500)


openImage = Image.open("..\\Images\\Boy.png")

img = ImageTk.PhotoImage(openImage)

lbl = Label(win, image=img)

lbl.place(x=30, y=60)


win.mainloop()


Rotate image using PIL



from tkinter import *

from PIL import ImageTk, Image


win = Tk()

win.title("Rotate Image")

win.geometry("300x300")


I = IntVar()

  

def Save(e):

  degree = I.get()

  openImage = Image.open("..\\Images\\Python.png")

  rotatedImage = openImage.rotate(degree)

  rotatedImage.save('..\\Images\\PythonRotated.png')

  pic1 = PhotoImage(file="..\\Images\\PythonRotated.png")

  lbl.config(image=pic1)

  lbl.image = pic1


scl1 = Scale(win, variable=I, from_=0, to=360, orient=HORIZONTAL)

scl1.bind("<ButtonRelease-1>", Save)

scl1.place(x=30, y=10)


openImage = Image.open("..\\Images\\Python.png")

img = ImageTk.PhotoImage(openImage)

lbl = Label(win, image=img)

lbl.place(x=30, y=60)


win.mainloop()


Thursday, November 26, 2020

Create QR codes, embed QR code in image, embed image in QR code, using Python

Create QRCODE


import qrcode


img = qrcode.make('Binoy Thomas')

print(type(img))   # <class 'qrcode.image.pil.PilImage'>

print(img.size)    # (290, 290)

img.save('QR.png')





Embed QRCode in image



import qrcode
from PIL import Image

img = Image.open('Anupam.jpg')
info = '''Actor Anupam Kher was born on 7 March 1955 in \
Shimla. He is regarded as an outstanding cineaste and is \
the recipient of 2 National Film Awards and 8 Filmfare \
Awards. Kher has appeared in over 500 films in several \
languages. His break-through performance was in Saaransh \
(1984), where he essayed the role of a septugenerian, when \
still in his 20's. His biography "Lessons Life Taught Me \
Unknowingly" is published by Penguin Random House.'''

qr = qrcode.QRCode(box_size=2)
qr.add_data(info)
qr.make()
Qr = qr.make_image()

pos = (img.size[0] - Qr.size[0], img.size[1] - Qr.size[1])

img.paste(Qr, pos)
img.save('Anupam1.png')



Embed image in QRCode



import qrcode
from PIL import Image

face = Image.open('AnupamSmall.jpg').crop((100, 40, 175, 125))

Qr = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_H)
Qr.add_data('I am Anupam')
Qr.make()
img = Qr.make_image().convert('RGB')

pos = ((img.size[0] - face.size[0])//2, (img.size[1] - face.size[1])//2)

img.paste(face, pos)
img.save('AnupamSmall.png')


Generate QR Code within GUI

import qrcode
from tkinter import *

qr = qrcode.QRCode(version=1, error_correction=qrcode.ERROR_CORRECT_L,
                   box_size=10, border=4)

win = Tk()
win.geometry("500x500")

S1 = StringVar()
S1.set("https://www.google.com")
ent = Entry(win, width=30, textvariable=S1, font=("Verdana", 16, "bold"))
ent.place(x=20, y=0)
ent.focus()

def generateQRCode():
  qr.add_data(S1)
  qr.make() # generate QR code
  img = qr.make_image()
  img.save("QRCode.png")
  pic = PhotoImage(file="QRCode.png")
  lbl = Label(win, image=pic)
  lbl.place(x=110, y=50)
  lbl.config(image=pic)
  lbl.image=pic

btnGenerate = Button(win, text="Generate", font=("Verdana", 16, "bold"), command=generateQRCode)
btnGenerate.place(x=185, y=400)

win.mainloop()

Saturday, November 14, 2020

Steganography using Python with tkinter

 https://www.section.io/engineering-education/steganography-in-python/




# pip install opencv-python

from tkinter import *

from PIL import Image, ImageTk

from tkinter import filedialog

import cv2

import numpy as np

import math


global path_image


image_display_size = 300, 300


def OnClick():

  global path_image

  path_image = filedialog.askopenfilename()

  load_image = Image.open(path_image)

  load_image.thumbnail(image_display_size, Image.ANTIALIAS)

  np_load_image = np.asarray(load_image)

  np_load_image = Image.fromarray(np.uint8(np_load_image))

  render = ImageTk.PhotoImage(np_load_image)

  img = Label(app, image=render)

  img.image = render

  img.place(x=20, y=50)


def Encrypt():

  global path_image

  data = txt.get(1.0, "end-1c")

  img = cv2.imread(path_image)

  data = [format(ord(i), '08b') for i in data]    # break image to binary chararacters

  _, width, _ = img.shape

  PixReq = len(data) * 3                 # algorithm to encode the image


  RowReq = PixReq/width

  RowReq = math.ceil(RowReq)


  count = 0

  charCount = 0

  for i in range(RowReq + 1):

    while(count < width and charCount < len(data)):

      char = data[charCount]

      charCount += 1

      for index_k, k in enumerate(char):

        if((k == '1' and img[i][count][index_k % 3] % 2 == 0) or (k == '0' and img[i][count][index_k % 3] % 2 == 1)):

          img[i][count][index_k % 3] -= 1

        if(index_k % 3 == 2):

          count += 1

        if(index_k == 7):

          if(charCount*3 < PixReq and img[i][count][2] % 2 == 1):

            img[i][count][2] -= 1

          if(charCount*3 >= PixReq and img[i][count][2] % 2 == 0):

            img[i][count][2] -= 1

          count += 1

    count = 0


  cv2.imwrite("EncryptedImage.png", img)


  success_label = Label(app, text="Encrypted!", bg='lavender', font=("Helvetica", 20))

  success_label.place(x=130, y=360)


app = Tk()

app.configure(background='lavender')

app.title("Encrypt")

app.geometry('400x400')


btnSelect = Button(app, text="Select PNG Image (Max 500 x 300)", command=OnClick)

btnSelect.place(x=100, y=10)


txt = Text(app, wrap=WORD, width=30)

txt.place(x=80, y=220, height=100)


encrypt_button = Button(app, text="Encode", bg='white', fg='black', command=Encrypt)

encrypt_button.place(x=180, y=328)


app.mainloop()

#############################################################################




import cv2
from tkinter import filedialog, Tk, Button, Label
from PIL import Image, ImageTk
import numpy as np

image_display_size = 500, 350

def decrypt():
  load = Image.open("EncryptedImage.png")
  load.thumbnail(image_display_size, Image.ANTIALIAS)
  load = np.asarray(load)
  load = Image.fromarray(np.uint8(load))
  render = ImageTk.PhotoImage(load)
  img = Label(app, image=render)
  img.image = render
  img.place(x=100, y=50)

  img = cv2.imread("EncryptedImage.png")
  data = []
  stop = False
  for index_i, i in enumerate(img):
    i.tolist()
    for index_j, j in enumerate(i):
      if((index_j) % 3 == 2):
        data.append(bin(j[0])[-1])  # first pixel
        data.append(bin(j[1])[-1])  # second pixel
        if(bin(j[2])[-1] == '1'):   # third pixel
          stop = True
          break
      else:
        data.append(bin(j[0])[-1])  # first pixel
        data.append(bin(j[1])[-1])  # second pixel
        data.append(bin(j[2])[-1])  # third pixel
    if(stop):
      break

  message = []
  for i in range(int((len(data)+1)/8)):  # join bits to form letters
    message.append(data[i*8:(i*8+8)])
  message = [chr(int(''.join(i), 2)) for i in message]  # join all letters to form the message.
  message = ''.join(message)
  message_label = Label(app, text=message, bg='lavender', font=("Times New Roman", 10))
  message_label.place(x=30, y=400)

app = Tk()
app.configure(background='lavender')
app.title("Decrypt")
app.geometry('600x600')

main_button = Button(app, text="Decrypt", bg='white', fg='black', command=decrypt)
main_button.place(x=250, y=10)
app.mainloop()





Digital Clock (Blessen Aby)




from tkinter import *

import time

import sys


root=Tk()

root.title("Digital Clock")


def get_time():

  time_string=time.strftime("%I:%M:%S %p")

  clock.config(text=time_string)

  clock.after(170, get_time)


clock = Label(root, font=("time", 90, "bold"), bg="green")

clock.pack()


get_time()


root.mainloop()


Saturday, October 24, 2020

Rolling text animation with Python

Logo.gif

from tkinter import *
from random import randint
from time import sleep

win = Tk()
win.geometry("750x500+0+0")

S00, S01, S02, S03, S04 = StringVar(), StringVar(), StringVar(), StringVar(), StringVar()
S05, S06, S07, S08, S09 = StringVar(), StringVar(), StringVar(), StringVar(), StringVar()
S10, S11, S12, S13, S14 = StringVar(), StringVar(), StringVar(), StringVar(), StringVar()
X, Y = 200, 13

lbl = Label(win, text = "", bg="black", fg="yellow", width=18, font=("Helvetica", 36, "bold"));    lbl.place(x=X-22, y=Y)
lbl00 = Label(win, textvariable = S00, bg="black", fg="#FFFF00", font=("Helvetica", 36, "bold"));  lbl00.place(x=X, y=Y)
lbl01 = Label(win, textvariable = S01, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl01.place(x=X+40, y=Y)
lbl02 = Label(win, textvariable = S02, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl02.place(x=X+80, y=Y)
lbl03 = Label(win, textvariable = S03, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl03.place(x=X+125, y=Y)

lbl04 = Label(win, textvariable = S04, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl04.place(x=X+160, y=Y)
lbl05 = Label(win, textvariable = S05, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl05.place(x=X+200, y=Y)
lbl06 = Label(win, textvariable = S06, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl06.place(x=X+240, y=Y)
lbl07 = Label(win, textvariable = S07, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl07.place(x=X+280, y=Y)

lbl08 = Label(win, textvariable = S08, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl08.place(x=X+358, y=Y)
lbl09 = Label(win, textvariable = S09, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl09.place(x=X+398, y=Y)
lbl10 = Label(win, textvariable = S10, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl10.place(x=X+438, y=Y)
lbl11 = Label(win, textvariable = S11, bg="black", fg="yellow", font=("Helvetica", 36, "bold"));   lbl11.place(x=X+460, y=Y)

pic1 = PhotoImage(file="Logo.gif")
lblLogo = Label(win, image=pic1);  lblLogo.place(x=50, y=0)

def roll(S, ch, lbl):
  for i in range(16):
    S.set(chr(65 + randint(0, 25)))
    sleep(.01)
    win.update_idletasks()
    S.set("   ")
    cols = ["#000000", "#111100", "#222200", "#333300",
            "#444400", "#555500", "#666600", "#777700",
            "#888800", "#999900", "#AAAA00", "#BBBB00",
            "#CCCC00", "#DDDD00", "#EEEE00", "#FFFF00"
           ]
    lbl.config(fg=cols[i])
  S.set(ch)

roll(S00, 'C ', lbl00);  roll(S01, 'O ', lbl01)
roll(S02, 'M ', lbl02);  roll(S03, 'P ', lbl03)
roll(S04, 'U ', lbl04);  roll(S05, 'T ', lbl05)
roll(S06, 'E ', lbl06);  roll(S07, 'R ', lbl07)
roll(S08, 'Q ', lbl08);  roll(S09, 'U ', lbl09)
roll(S10, 'I ', lbl10);  roll(S11, 'Z ', lbl11)

win.mainloop()

Thursday, October 8, 2020

Independence Day Quiz (tkinter)

 


 0.png
 2.png
 4.png

 6.png


from tkinter import *

win = Tk()
win.geometry("1000x650")

ctr, I = 0, IntVar()
QList = ["Who said 'Freedom is my birthright and I shall have it'?",
         "This is Bharat Mata, 1905; the first instance of the concept of Bharat Mata appearing in art. Identify the painter.",
         "Who said 'Give me your blood and I shall give you freedom'?",
         "Our national flag was modified several times during the freedom movement. Identify the flag used during the Swadeshi Movement of 1906.",
         "Who announced the permission to have full self-government to British India?",
         "This train station sign board is in Tamil Nadu, in remembrance to the freedom fighter and revolutionary Vanchi Maniachi Vanchinatha Iyer, popularly known as Vanchi. Who did he assassinate? . Who was Robert William Ashe?",
         "Who was the last Governor-General of India?",
         "The Indian Independence Act was repealed in which article of the Constitution of India?",
         "An announcement of a Malayalam movie based on the life of a freedom fighter from Malapuram was done recently causing a lot of backlash to the director and actor. Whose biopic is it?",
         "The Indian Muslim Movement was led by ...",
         "Which battle is said to be the most important one for the East India Company?",
         "By law, what type of cloth material is used for making national flag?",
         '''
         "Who designed the present Triranga (tricolor) national flag?",
         "Who is known as Kerala Gandhi?",
         "Which famous freedom fighter was known as 'Bharatha Kokila' or the Nightingale of Indai?",
         "Which act introduced by British authorized the government to imprison any person suspected of terrorism for up to two years without trial?",
         "Which Act expanded the participation of Indians in the government?",
         "Who carried out the partition of Bengal?",
         "Who was the Law Minister in the 1st Indian government headed by Jawaharlal Nehru ministry of 1947?",
         "At the Lahore Session of the Indian National Congress, the tri-colour was unfurled for the first time.Which year was that?",
         "The First Indian National Army was founded by?",
         "Which of the following is not a part of protest against salt tax?",
         "Who set up the Indian Independence League?",
         "The first weekly paper published by the Indian National Congress in 1889?",
         "Where was the Civil disobedience movement launched in1922?",
         "Where did the Congress Working committee first accept the idea of the Quit India Movement?", 
         "When did Gandhiji start the Sabarmati Ashram?",
         "What is the nick name of the English East India Company?",
         '''
        ]

AList = [["a. Lala Lajpat Rai",           "b. Bal Ganga Dhar Tilak",      "c. Bipin Chandra Pal",          "d. Netaji Subhas Chandra Bose", 2, "b. Bal Ganga Dhar Tilak"],
         ["a. Raveendranatha Tagore",     "b. Abaneedranath Tagore",      "c. Nandalal Bose",              "d. Amritha Shergil",            2, "b. Abaneedranath Tagore"],
         ["a. Bal Ganga Dhar Tilak",      "b. Bipin Chandra Pal",         "c. Netaji Subhas Chandra Bose", "d. Lala Lajpat Rai",            3, "c. Netaji Subhas Chandra Bose"],
         ["a. Clement Attlee",            "b. Louis Mountbatten",         "c. Lord Dalhousie ",            "d. Lord Wavell",                2, "b. Louis Mountbatten"], 
         ["a. Lord Wavell",               "b. Lord Willingdon",           "c. Lord Mountbatten",           "d. James Brown",                4, "d. James Brown"], 
         ["a. Robert Ashe, tax colletor", "b. Charles Tegart, policeman", "c. John Nicholson, armyman",    "d. Lord Mayo, Viceroy.",        1, "a. Robert Ashe, tax colletor"],
         ["a. Article 221",               "b. Article 144",               "c Article 395",                 "d. Article 345",                4, "d. Article 345"],
         ["a. Kunjahammed Haji",          "b. Abdur Rahiman",             "c. Moidu Moulavi",              "d. Abdul Rahim",                1, "a. Kunjahammed Haji"],
         ["a. Muhammad Ali Jinnah",       "b. Shaukat Ali",               "c. Maulana Azad",               "d. Rehamt Ali",                 2, "b. Shaukat Ali"],
         ''' 
         ["a. Capture of Lucknow", "b. Battle of Plassey", "c. Battle of Phillora", "d. Battle of Panipat", 2],
         ["a. Khadi cloth", "b. Cotton cloth", "c. Naylon cloth", "d. Jute cloth", 1],
         ["a. Mahatma Gandhi", "b. Pingalivenkayya", "c. Surayya Tyabji", "d.Panduranga Reddy",2],
         ["a. Abdul Gafoor Khan", "b. Ayyankali", "c. K. Kelappan", "d. Sree Narayana Guru", 3],
         ["a. Sarojini Naidu", "b. Lala Lajpat Rai", "c. Laxmi bai", "d. Abdul Gafoor Khan", 1],
         ["a. Charter Act", "b. Rowlatt Act", "c.Defence of India Act", "d. Salt Act", 2],
         ["a. Govt. of India Act,1909", "b. Govt. of India Act,1919", "c. Govt. of India Act,1935", "d. Govt. of India Act,1996", 2], 
         ["a. Lord Curzon", "b. Lord Dufferin", "c. Lord Minto", "d. James Broun", 1],
         ["a. C.D.Deshmukh", "b. Baldev Singh", "c. John Mathai", "d. B.R.Ambedkar", 4],
         ["a. 1929", "b. 1931", "c. 1927", "d. 1926", 1],
         ["a. Bhagat Singh", "b. Capt.Mohansingh", "c. Subhash Chandra Bose", "d.Wallabhai Patel", 2],
         ["a. Dandi Satyagraha", "b. Dharasana Satyagraha", "c. Non-Cooperation Movement", "d. Mahatma Gandhi", 3], 
         ["a. Rash Bihari Bose", "b. Baldev Singh", "c. C.D.deshmukh", "d. Ghan Abdul", 1],
         ["a. Hindi Akhbar", "b. Voice of India", "c. Marathi Samachar", "d. India Times", 2],
         ["a. Bihar", "b. Champaran", "c. Lucknow", "d. Bardoli", 4],
         ["a. Wardha", "b. Sabarmati", "c. Bardoli", "d. Champaran", 1],
         ["a. 1915", "b. 1916", "c. 1920", "d. 1918", 2],
         ["a. William Company", "b. James Company", "c. John Company", "d. Clement Company", 3]
         '''
        ]

def Next():
  global ctr
  lblVerdict.config(text="")
  rbtnA1.place(x=110, y=240);  rbtnA2.place(x=110, y=280)
  rbtnA3.place(x=110, y=320);  rbtnA4.place(x=110, y=360)
  btnStart.config(state=DISABLED);  btnNext.config(state=DISABLED);  btnCheck.config(state=NORMAL)
  
  msgQNo.config(text="Q " + str(ctr+1))
  msgQues.config(text=QList[ctr])
  rbtnA1.config(text=AList[ctr][0]);  rbtnA2.config(text=AList[ctr][1])
  rbtnA3.config(text=AList[ctr][2]);  rbtnA4.config(text=AList[ctr][3])
  
  ctr += 1
  rbtnDum.select()
  lblCorrAns.config(text="")

  if ctr == 2 or ctr == 4 or ctr == 6:
    pic = PhotoImage(file=str(ctr) + ".png")
    lblImage.config(image=pic)
    lblImage.image = pic
  else:
    pic = PhotoImage(file="0.png")
    lblImage.config(image=pic)
    lblImage.image = pic

def Check():
  print(I.get())
  if I.get() == AList[ctr-1][4]:
    lblVerdict.config(text="Correct", fg="blue")
    print(AList[ctr-1][5])
  else:
    lblVerdict.config(text="Incorrect", fg="red")
    s = AList[ctr-1][5]
    print(s)              
    lblCorrAns.config(text=s, fg="blue")
  btnCheck.config(state=DISABLED);  btnNext.config(state=NORMAL)

  if ctr == len(QList):
    btnNext.config(state=DISABLED)

msgQNo    = Message(win, font=("Arial", 20, "bold"), width=75);     msgQNo.place(x=10, y=20)
msgQues   = Message(win, font=("Arial", 20, "bold"), width=650);    msgQues.place(x=100, y=20)

picStart = PhotoImage(file="Start.png")
btnStart = Button(win, command=Next, image=picStart);  btnStart.place(x=100, y=415)

picNext = PhotoImage(file="Next.png")
btnNext = Button(win, command=Next, image=picNext, state=DISABLED);  btnNext.place(x=200, y=415)

picCheck = PhotoImage(file="Check.png")
btnCheck = Button(win, command=Check, image=picCheck, state=DISABLED);  btnCheck.place(x=300, y=415)

rbtnA1    = Radiobutton(win, font=("Arial", 14, "bold"), variable=I, value=1)
rbtnA2    = Radiobutton(win, font=("Arial", 14, "bold"), variable=I, value=2)
rbtnA3    = Radiobutton(win, font=("Arial", 14, "bold"), variable=I, value=3)
rbtnA4    = Radiobutton(win, font=("Arial", 14, "bold"), variable=I, value=4)
rbtnDum   = Radiobutton(win, font=("Arial", 10, "bold"), variable=I, value=5) 

lblImage = Label(win);  lblImage.place(x=450, y=150)

lblVerdict = Label(win, font=("Arial", 20, "bold"));  lblVerdict.place(x=200, y=540)
lblCorrAns = Label(win, font=("Arial", 20, "bold"));  lblCorrAns.place(x=370, y=540)

win.mainloop()






Saturday, September 26, 2020

MP4 to GIF Converter (Using moviepy.editor)

import moviepy.editor as mpy

 

clip = mpy.VideoFileClip("Valayosai gala gala.mp4")

myClip = clip.subclip(0, 5)   # From 0s to 5s


#myClip.resize(0.5)           # width & heigth halved

#myClip.resize(width=800)     # Height computed automatically


myClip.write_gif("Valayosai.gif")


Friday, September 25, 2020

Python-MySQL Interface project (Text based)

import mysql.connector as mc

from art import text2art as t2a


def Display(recs, nor, src):

  if src != "delete":

    print("\nRoll    F_Name       L_Name    Sex   Average")

    print("====    ======       ======    ===   =======")

  if nor == 1:

    print("%3s   %-11s  %-11s  %1s %10s" % (recs[0], recs[1], recs[2], recs[3], recs[4]))

  else:

    for rec in recs:

      print("%3s   %-11s  %-11s  %1s %10s" % (rec[0], rec[1], rec[2], rec[3], rec[4]))

  print("\n", nor, "records displayed")


def display():

  conn = mc.connect(host="localhost", user="root", passwd="root", database="test")

  cur = conn.cursor()

  cur.execute("SELECT * FROM students")

  records = cur.fetchall()

  count = cur.rowcount

  if count == 0:

    print("Empty table")

  else:

    Display(records, cur.rowcount, "display")

  conn.close()

  input("\nPress any key to continue ...\n")


def add():

  conn = mc.connect(host="localhost", user="root", passwd="root", database="test")

  cur = conn.cursor()


  role = int(input("Enter roll number: "))

  fnm  = input("Enter first name: ")

  lnm  = input("Enter last name: ")

  s    = input("Enter sex: ")

  aver = float(input("Enter average: "))


  sql = "INSERT INTO students(roll, fname, lname, sex, avg) VALUES(%s, %s, %s, %s, %s)"

  values = (role, fnm, lnm, s, aver)

  cur.execute(sql, values)

  conn.commit()

  conn.close()

  input("\nPress any key to continue ...\n")

  

def search():

  conn = mc.connect(host="localhost", user="root", passwd="root", database="test")

  cur = conn.cursor()

  field = input("Enter field to be searched: ")


  if field == "roll":

    cond  = input("Enter roll to search for: ")

    query = "SELECT * FROM students WHERE roll = '" + cond + "'"

  elif field == "fname":

    cond  = input("Enter fname to search for: ")

    query = "SELECT * FROM students WHERE fname = '" + cond + "'"

  elif field == "lname":

    cond  = input("Enter lname to search for: ")

    query = "SELECT * FROM students WHERE lname = '" + cond + "'"

  elif field == "sex":

    cond  = input("Enter sex to search for: ")

    query = "SELECT * FROM students WHERE sex = '" + cond + "'"

  elif field == "avg":

    opt   = input("Search for >, <, >=, <=, == or !=: ")

    cond  = input("Enter avg to search for: ")

    query =  "SELECT * FROM students WHERE avg " + opt + " " + cond


  print()

  cur.execute(query)

  records = cur.fetchall()

  if cur.rowcount == 0:

    print("No records returned")

  else:

    Display(records, cur.rowcount, "search")

  conn.close()  

  input("\nPress any key to continue ...\n")

  

def modify():

  role = int(input("Enter roll no of record to modify: "))

  conn = mc.connect(host="localhost", user="root", passwd="root", database="test")

  cur = conn.cursor()

  query = "SELECT * FROM students WHERE roll = " + str(role)

  

  print(query)

  cur.execute(query)

  rec = cur.fetchall()

  Display(rec, 1, "modify")

  

  ans = input("Are you sure you wish to update this record? (Y/N) ")

  if ans.upper() == 'Y':

    fnm  = input("Enter new first name   : ")

    lnm  = input("Enter new last name    : ")

    sx   = input("Enter sex              : ")

    aver = input("Enter new average: ")


    cur.execute("UPDATE students SET fname = '" + fnm  + "' WHERE roll = " + str(role))

    cur.execute("UPDATE students SET lname = '" + lnm  + "' WHERE roll = " + str(role))

    cur.execute("UPDATE students SET sex   = '" + sx   + "' WHERE roll = " + str(role))

    cur.execute("UPDATE students SET avg   = '" + aver + "' WHERE roll = " + str(role))

    conn.commit()

  conn.close()

  input("\nPress any key to continue ...\n")


def delete():

  role = input("\nEnter roll no of record to delete: ")

  conn = mc.connect(host="localhost", user="root", passwd="root", database="test")

  cur = conn.cursor()

  query = "SELECT * FROM students WHERE roll = " + role

  cur.execute(query)

  rec = cur.fetchone()

  if cur.rowcount == 1:

    Display(rec, 1, "delete")

    ans = input("\nDelete this record? (Y/N)")

    if ans.upper() == 'Y':

      cur.execute("DELETE FROM students WHERE roll = " + role)

      conn.commit()

  else:

    print("Record not found")

  input("\nPress any key to continue ...\n")

  

choice = 0

while True:

  print(t2a("      STUDENT     DATABASE"))

  print("\t\t\t\t\t\t\t\tPrepared by T. V. Thomas (Regn. No. __)")

  print("1. Display all records")

  print("2. Add record")

  print("3. Search record")

  print("4. Modify record")

  print("5. Delete record")

  print("6. Display sorted records")

  print("0. Exit")

  choice = int(input("Enter your choice: "))


  if choice == 1:

    display()

  elif choice == 2:

    add()

  elif choice == 3:

    search()

  elif choice == 4:

    modify()

  elif choice == 5:

    delete()

  elif choice == 6:

    pass

  elif choice == 0:

    break

  else:

    print("Wrong choice")