Python Coding

Tic Tac Toe Game
This project is developed in Python using Anaconda and Spyder. This GUI based and the library used is Tkinter.

Output:


















YouTube Tutorial Link: TicTacToe Game

Python Code:
from tkinter import *
from PIL import Image, ImageTk
expression = ""
num=' '
m=1

buttons=[]
bgcol1='white'
bgcol2='lightblue'
fgcol1='blue'
fgcol2='red'
canvascol='lightgreen'
font1 = "Helvetica 12 bold"
bgimage=""
btimagex=""
btimageo=""
btimage=""

def bg_image():
    global bgimage,btimagex,btimageo,btimage
    im  = Image.open("bgimage.png")
    btx = Image.open("btimagex.png")
    bto = Image.open("btimageo.png")
    bt  = Image.open("btimage.png")
 
    bgimage=ImageTk.PhotoImage(im)
    btimagex=ImageTk.PhotoImage(btx)
    btimageo=ImageTk.PhotoImage(bto)
    btimage=ImageTk.PhotoImage(bt)

def check_win():
global buttons
win_cond = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
for each in win_cond:
if buttons[each[0]-1]['text']!=' ' and buttons[each[0]-1]['text'] == buttons[each[1]-1]['text'] and buttons[each[1]-1]['text'] == buttons[each[2]-1]['text']:
    return 1,buttons[each[0]-1],buttons[each[1]-1],buttons[each[2]-1]
return -1,buttons[each[0]-1],buttons[each[1]-1],buttons[each[2]-1]

def press(button):
global num,m,btimage,btimagex,btimageo
if m % 2 == 0:
num='O'
fgcol=fgcol1
else:
num='X'
fgcol=fgcol2
button.config(text=num,fg=fgcol) 
if num=='X':
   button.config(image=btimagex)     
elif num=='O':
   button.config(image=btimageo) 
else:
   button.config(image=btimage) 

m=m+1
ret,b1,b2,b3=check_win()
lbl1.config(text="Move :"+str(m))
lbl1.place(x=100-len(lbl1.config('text')[4]),y=35)
#print(len(lbl1.config('text')[4]),lbl1.config('text')[4])
if ret==1:
print("Player "+num+" Won")
lbl1.config(text="Player "+num+" Won")
lbl1.place(x=100-len(lbl1.config('text')[4]),y=35)
#print(len(lbl1.config('text')[4]),lbl1.config('text')[4])
button_color(b1,num)
button_color(b2,num)
button_color(b3,num)
button_enable(DISABLED)
exit()

def button_color(button,num):
    global bgcol2,btimage,btimagex,btimageo
    button.config(background=bgcol2) 
    button.config()
 
def button_enable(flag):
    global buttons
    for i in range(3):
    for j in range(3):
       buttons[i*3+j].config(state=flag)

def disp(x1,y1):
    global buttons,bgcol1,font1,fgcol,btimage
    button = Button(gui, image=btimage,font=font1,border=1,text=num,
command=lambda: press(button),height=65, width=65 )
    button.place(x=65*(x1)+36,y=65*(y1)+60)
    buttons.append(button)

if __name__ == "__main__":
gui = Tk()
#gui=Toplevel()
bg_image()

gui.title("tic tac")
gui.geometry("275x320")

lbl=Label(gui,font=font1,image=bgimage)
lbl.place(x=0,y=0)
lbl1=Label(gui,text="Move 1",font=font1)
lbl1.place(x=100-len(lbl1.config('text')),y=35)
#lbl1.pack()
for i in range(3):
    for j in range(3):
        disp(i,j)
button_enable(NORMAL)

gui.mainloop()


Background Image used for Tic tacToe Game





Calculator in GUI
This is a Python program on Calculator. On pressing AC button the number buttons are enabled and on pressing OFF button the buttons are disabled. On pressing AC button the light start blinking. All mathematical calculation can be performed. In this we have used background image of calculator and numbers buttons are added. We have used tkinter module for GUI.

YouTube Tutorial:  Calculator Project

Output


Python Code for Calculator
from tkinter import *
from PIL import Image, ImageTk
expression = ""

font1 = font=("Open Sans Standard",11,"bold");
fontoff = font=("Open Sans Standard",6,"bold");
fontlbl = font=("Open Sans Standard",16,"normal");
fgcol='white'
bgcol='#8e8b9c'
bgcol2='#545164'
bgcol1="#bd7a95"
bgcolwhite="white"
borderw=0
btimage=""
expression_field=""
entry_flag=0

def button_enable(flag):
    global expression_field,entry_flag
    expression_field.config(state=flag,bg=bgcolwhite)
    if flag==DISABLED:
       entry_flag=0
       lblblink.config(bg=bgcol1)
    else:
       entry_flag=1
       lblblink.config(bg="red")
       change_color()

def change_color():
    global entry_flag
    if entry_flag==0:
        return
    current_color = lblblink.cget("background")
    next_color = "pink" if current_color == "red" else "red"
    lblblink.config(background=next_color)
    gui.after(500, change_color)

def make_button(gui,ptext,pfn,row1,col):
global btimage
if ptext=="+": 
  button1 = Button(gui, text=ptext, fg=fgcol, bg=bgcol2, font=font1,borderwidth=borderw,
command=lambda: press(pfn), height=3, width=2,padx=0,pady=0)
elif pfn=="-" or pfn=="*" or pfn=="%" or pfn=="/": 
  button1 = Button(gui, text=ptext, fg=fgcol, bg=bgcol2, font=font1,borderwidth=borderw,
command=lambda: press(pfn), height=1, width=2,padx=0,pady=0)
elif ptext=="C" or ptext=="AC": 
  button1 = Button(gui, text=ptext, fg=fgcol, bg=bgcol1, font=font1,borderwidth=borderw,
command=lambda: press(pfn), height=1, width=2,padx=0,pady=0)
else:
  button1 = Button(gui, text=ptext, fg=fgcol, bg=bgcol, font=font1,borderwidth=borderw,
command=lambda: press(pfn), height=1, width=2,padx=0,pady=0)
button1.place(x=(col*45)+24,y=(row1*41)+254)
return button1
 
def bg_image():
    global bgimage,btimage
    im  = Image.open("calculator.png") 
    bgimage=ImageTk.PhotoImage(im)
    bt  = Image.open("button.png") 
    btimage=ImageTk.PhotoImage(bt)
 
def press(num):
global expression ,entry_flag
if entry_flag==1:
   expression = expression + str(num)
   equation.set(expression)

def equalpress():
try:
global expression
total = str(eval(expression))
equation.set(total)
expression = ""
except:
equation.set(" error ")
expression = ""

def clear():
global expression
expression = ""
equation.set("")

if __name__ == "__main__":
gui = Tk()
#gui=Toplevel()
gui.configure(background="light green")
gui.title("GUI Calculator")
gui.geometry("250x425")
bg_image()
lbl=Label(gui,font=font1,image=bgimage)
lbl.place(x=0,y=0)
lblblink=Label(gui,text="  ",font=fontoff,bg='red',borderwidth=2, relief="solid")
lblblink.place(x=30-len(lblblink.config('text')),y=20)
equation = StringVar()
expression_field = Entry(gui, textvariable=equation,font=fontlbl,bg=bgcol,width=15,borderwidth=2)
expression_field.place(x=30,y=118)

equation.set('0')

for i in range(3):
  for j in range(3,0,-1):
     val=11-(i*3+j+1)
     b=make_button(gui,val,val,i,j)

equal = Button(gui, text='=', fg=fgcol, bg=bgcol2, font=font1,borderwidth=0,
command=equalpress, height=1, width=2)
equal.place(x=(3*45)+24,y=(3*41)+256)

clear = Button(gui, text=' C ', fg=fgcol, bg=bgcol1, font=font1,borderwidth=0,padx=0,pady=0,
command=clear, height=1, width=2)
clear.place(x=(0*45)+24,y=(2*41)+296)

button_on = Button(gui, text=' AC', fg=fgcol, bg=bgcol1, font=font1,borderwidth=0,padx=0,pady=0,
command=lambda:button_enable(NORMAL), height=1, width=3)
button_on.place(x=(0*45)+24,y=(2*41)+256)

button_off = Button(gui, text='OFF', fg=fgcol, bg=bgcol2, font=font1,borderwidth=0,padx=0,pady=0,
command=lambda:button_enable(DISABLED), height=1, width=3)
button_off.place(x=(0*45)+24,y=(2*41)+130)

make_button(gui," % ","%",0,0)
make_button(gui," / ","/",1,0)
make_button(gui,"0","0",3,1)
make_button(gui,".",".",3,2)
make_button(gui,"*","*",0,4)
make_button(gui,"-","-",1,4)
make_button(gui,"+","+",2,4)
button_enable(DISABLED)
# start the GUI
gui.mainloop()



Image used for Calculator:



Graph

Output


Python Code for making Bar,Stack,Pie etc charts


import numpy as np
import matplotlib.pyplot as plt

def leg1(ax,ptitle,xt,yt,xlabel,ylabel)  :
  ax.set_title(ptitle)
  ax.set_yticks(xt)
  ax.legend(loc='upper left',shadow=True,bbox_to_anchor=(-.34,1.2),prop={'size': 8},)
  ax.set_xlabel(xlabel)
  ax.set_ylabel(ylabel)
  plt.yticks(np.arange(5),xt)

def legpie(ax,ptitle,xt,yt)  :
  ax.set_title(ptitle)
  ax.legend(loc='upper left',shadow=True,bbox_to_anchor=(-.5,1),prop={'size': 8},)
xplot1=[72,120,104,91,72]
xplot2=[130,307,94,88,308]
yplot=['TN','MH','BH','WB','MP']
fig,ax=plt.subplots(2,2)
fig.suptitle("List of Graph")
fig.set_facecolor('red')
fig.set_edgecolor('black')
fig.patch.set_alpha(.4)
#fig.tight_layout()
fig.subplots_adjust(hspace=.6,wspace=0.5)

ax[0,0].plot(yplot,xplot1,color='green')
ax[0,0].plot(yplot,xplot2,color='red')
ax[0,0].bar(yplot,xplot1,width=.3,color='green',label='Population')
ax[0,0].bar(yplot,xplot2,width=.2,color='red',label='Density')
leg1(ax[0,0],'Bar Chart',xplot1,yplot,'<---Population--->','<--States-->')

ax[0,1].bar(yplot,xplot1,width=.2,color='green',label='Population')
ax[0,1].bar(yplot,xplot2,width=.2,color='red',label='Density',bottom=xplot1)
leg1(ax[0,1],'Stack Bar',xplot1,yplot,'<---Population--->','<--States-->')

ax[1,0].pie(xplot1,labels=yplot,autopct='%1.1f%%',)
legpie(ax[1,0],'Pie Chart showing Population ',xplot1,yplot)

ax[1,1].pie(xplot2,labels=yplot,autopct='%1.1f%%',)
c=plt.Circle((0,0),.8,color='white')
p=plt.gcf()
p.gca().add_artist(c)
legpie(ax[1,1],'Dounut Chart showing Density',xplot1,yplot)





No comments:

Post a Comment