#this program explains how to achieve the blackjack game
#the key points to note here are
#pop funtion,using the same code of function to avoid repetition
#load images from file to frame,shuffling of cards,calculating scores
#then use of the global keyword to avoiding shadowing of the global variable inside the function
import tkinter as tkinter
import random
def load_images(card_images):
suits=['heart','club','diamond','spade']
face_cards=['jack','queen','king']
#for each suit retrieve the image for the cards
for suit in suits:
#first the number cards 1 to 10
for card in range(1,11):
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((card,image))
#next the Face Cards
for card in face_cards:
name = 'cards/{}_{}.{}'.format(str(card),suit,'png')
image = tkinter.PhotoImage(file = name)
card_images.append((10,image))
def deal_card(frame):
#pop the next card of the top of the deck
next_card= deck.pop(0)
#add the image to the label and display the label
tkinter.Label(frame,image=next_card[1],relief = 'raised').pack(side = 'left')
#now return the cards face value
return next_card
def deal_dealer():
dealer_score= score_hand(dealer_hand)
while 0 < dealer_score <17:
dealer_hand.append(deal_card(dealer_card_frame))
dealer_score= score_hand(dealer_hand)
dealer_score_label.set(dealer_score)
player_score = score_hand(player_hand)
if player_score>21:
resulttext.set('Dealer Wins!')
elif dealer_score > 21 or dealer_score player_score:
resulttext.set('Dealer Wins!')
else:
resulttext.set('Draw!')
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set ('Dealer Wins')
# def deal_player():
# deal_card(player_card_frame)
def deal_player():
player_hand.append(deal_card(player_card_frame))
player_score= score_hand(player_hand)
player_score_label.set(player_score)
if player_score>21:
resulttext.set ('Dealer Wins')
#below code is used for testing the global,local shadowing concept
# global player_score
# global player_ace
# card_value = deal_card(player_card_frame)[0]
# if card_value ==1 and not player_ace:
# player_ace = True
# card_value = 11
# player_score = player_score + card_value
# # if we would bust,check if there is an ace and subtract
# if player_score>21 and player_ace:
# player_score = player_score - 10
# player_ace = False
# player_score_label.set(player_score)
# if player_score>21:
# resulttext.set("Dealer Wins")
# print(locals())
def score_hand(hand):
#calculate the total score of all cards in the list
# only one can have the value 11,and this will be reduce to 1 if the hand would bust.
score = 0
ace = False
for next_card in hand:
card_value = next_card[0]
if card_value == 1 and not ace:
ace = True
card_value = 11
score = score + card_value
#if we would bust ,check if there is an ace and subtract 10
if score > 21 and ace:
score =score - 10
ace = False
return score
mainwindow = tkinter.Tk()
#setup the screens and frame for the dealer and the player
mainwindow.title("blackjack")
mainwindow.geometry("640x480")
mainwindow.configure(background = "green")
resulttext = tkinter.StringVar()
result = tkinter.Label(mainwindow,textvariable = resulttext)
result.grid(row=0,column=0,columnspan=3)
card_frame= tkinter.Frame(mainwindow,relief = 'sunken',borderwidth = 1,background = 'green')
card_frame.grid(row=1,column=0,sticky = 'ew',columnspan = 3,rowspan=2)
dealer_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Dealer',background ='green',fg='white').grid(row=0,column=0)
tkinter.Label(card_frame,textvariable = dealer_score_label,background ='green',fg='white').grid(row=1,column=0)
#embedded Frame hold the card images
dealer_card_frame=tkinter.Frame(card_frame,background = 'green')
dealer_card_frame.grid(row=0,column=1,sticky='ew',rowspan=2)
player_score_label = tkinter.IntVar()
tkinter.Label(card_frame,text = 'Player',background ='green',fg='white').grid(row=2,column=0)
tkinter.Label(card_frame,textvariable = player_score_label,background ='green',fg='white').grid(row=3,column=0)
#embedded Frame hold the card images
player_card_frame=tkinter.Frame(card_frame,background = 'green')
player_card_frame.grid(row=2,column=1,sticky='ew',rowspan=2)
button_frame = tkinter.Frame(mainwindow)
button_frame.grid(row=3,column=0,columnspan = 3,sticky = 'w')
dealer_button=tkinter.Button(button_frame,text = 'Dealer',command = deal_dealer)
dealer_button.grid(row=0,column=0)
player_button=tkinter.Button(button_frame,text = 'Player',command = deal_player)
player_button.grid(row=0,column=1)
#load cards
cards = []
load_images(cards)
# print(cards)
# print(id(cards))
#create a new deck of cards and shuffle them
deck = list(cards)
random.shuffle(deck)
#Create the list to store the dealers and players hands
dealer_hand = []
player_hand = []
deal_player()
dealer_hand.append(deal_card(dealer_card_frame))
deal_player()
mainwindow.mainloop()
Saturday, 7 April 2018
Python - function challenge - blackjack game - Day 22(after 1 day)
Friday, 6 April 2018
Python function -circle challenge 1 - Day 21(after 1 day)
#instead of using the for loop outside we can plot it in the parabol
#funtion itself
import math
import tkinter
def parabola(page,size):
for x in range(-size,size):
y = x * x/size
plot(page,x,y)
#the formula behind this is for circle it is enough to draw one quadrant and
#then negating it the axis will provide the symmetry and make an circle
#ie .. we have y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
#we want y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
#but minus y is actually -y = h - (math.sqrt(radius ** 2 -((x-g)**2)))
#so we add 2 * h back onto -y
def circle(page,radius,g,h):
for x in range(g,g + radius):
y = h + (math.sqrt(radius ** 2 -((x-g)**2)))
plot(page,x,y)
plot(page,x,2* h - y)
plot(page,2 * g - x,y)
plot(page,2 * g - x,2* h - y)
def draw_axes(page):
page.configure(scrollregion=(-200,-200,200,200))
page.create_line(-200,0,200,0, fill="blue")
page.create_line(0,200,0,-200, fill="blue")
def plot(canvas,x,y):
canvas.create_line(x,-y,x+1,-y+1,fill="red")
mainwindow = tkinter.Tk()
mainwindow.title("Parabola")
mainwindow.geometry("640x480")
canvas = tkinter.Canvas(mainwindow,width=640,height= 480)
canvas.grid(row=0,column=0)
print(id(canvas))
draw_axes(canvas)
parabola(canvas,100)
parabola(canvas,150)
circle(canvas,100,100,100)
circle(canvas,100,100,-100)
circle(canvas,100,-100,100)
circle(canvas,100,-100,-100)
circle(canvas,30,30,30)
circle(canvas,30,30,-30)
circle(canvas,30,-30,30)
circle(canvas,30,-30,-30)
# for x in range(-100,100):
# y = parabola(x)
# plot(canvas,x,-y)
mainwindow.mainloop()
Python function scope - Day 20(after 20 days)
#this will explain the scope of the variable
#we can use locals() to know the variable in that scopre,this can be used only inside functions
import tkinter
def parabola(x):
y = x * x/100
return y
def draw_axes(canvas):
#the canvas variable here is different from the canvas outside
#of this function
# canvas.update
#here the x and y origin are not fetching properly so hardcoded the values
# x_origin = canvas.winfo_width ()/2
# y_origin = canvas.winfo_height()/2
# x_origin = canvas.winfo_width ()
# y_origin = canvas.winfo_height()
canvas.configure(scrollregion=(-200,-200,200,200))
canvas.create_line(-200,0,200,0, fill="blue")
canvas.create_line(0,200,0,-200, fill="blue")
#this will give the object location(address),we can differentiate object of same names
#using this id()
print(id(canvas))
print(locals())
def plot(canvas,x,y):
canvas.create_line(x,y,x+1,y+1,fill="red")
mainwindow = tkinter.Tk()
mainwindow.title("Parabola")
mainwindow.geometry("640x480")
canvas = tkinter.Canvas(mainwindow,width=320,height= 480)
canvas.grid(row=0,column=0)
#we have created two canvas to show how the scope works
canvas2 = tkinter.Canvas(mainwindow,width=320,height= 480)
canvas2.grid(row=0,column=1)
print(id(canvas))
print(id(canvas2))
draw_axes(canvas)
draw_axes(canvas2)
for x in range(-100,100):
y = parabola(x)
plot(canvas,x,-y)
mainwindow.mainloop()
Thursday, 15 March 2018
Python function eg - Day 20
def python_food():
print("Spinach is good for health")
python_food()
print (python_food())
def center_text():
width = 50
text = 'Spinach is good for health'
leftalignment = (width - len(text))//2
print(' '*leftalignment,text)
center_text()
print('='*20)
def center_text1(text):
width = 50
leftalignment = (width - len(text))//2
print(' '*leftalignment,text)
center_text1('Spinach is Good for Health')
center_text1('Excecise is goood for body')
center_text1('Life is worth living')
center_text1('Love yourself')
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
Python tkinter - Calculator GUI - Day 20
import tkinter
keys = [[('C','1'),('CE','1')],
[('7','1'),('8','1'),('9','1'),('+','1')],
[('4','1'),('5','1'),('6','1'),('-','1')],
[('1','1'),('2','1'),('3','1'),('*','1')],
[('0','1'),('=','1'),('/','1')]]
mainWindowPadding = 10
mainWindow = tkinter.Tk()
mainWindow.title("Calculator")
mainWindow.geometry("800x480-8+200")
mainWindow["padx"]= mainWindowPadding
result = tkinter.Entry(mainWindow)
result.grid(row=0,column=0,sticky = 'nsew')
keypad = tkinter.Frame(mainWindow)
keypad.grid(row=1,column=0,sticky = 'nsew')
row = 0
for keyrow in keys:
column = 0
for key in keyrow:
tkinter.Button(keypad,text = key[0]).grid(row=row,column=column,
columnspan = key[1],sticky ='ew')
column+=1
row+=1
mainWindow.update()
mainWindow.minsize(keypad.winfo_width()+mainWindowPadding,result.winfo_height()
+keypad.winfo_height())
mainWindow.maxsize(keypad.winfo_width()+50 + mainWindowPadding,result.winfo_height()+50
+ keypad.winfo_height())
mainWindow.mainloop()
Wednesday, 14 March 2018
Python tkinter advanced gui - Day 19
import tkinter
import os
mainwindow = tkinter.Tk()
mainwindow.title("GRID DEMO")
mainwindow.geometry('600x480-8-200')
label =tkinter.Label(mainwindow,text ='tkinter grid demo label')
label.grid(row=0,column=0,columnspan = 3)
mainwindow.columnconfigure(0,weight=1)
mainwindow.columnconfigure(1,weight=1)
mainwindow.columnconfigure(2,weight=3)
mainwindow.columnconfigure(3,weight=3)
mainwindow.columnconfigure(4,weight=3)
mainwindow.rowconfigure(0,weight=1)
mainwindow.rowconfigure(1,weight=10)
mainwindow.rowconfigure(2,weight=1)
mainwindow.rowconfigure(3,weight=3)
mainwindow.rowconfigure(4,weight=3)
filelist =tkinter.Listbox(mainwindow)
filelist.grid(row=1,column=0,sticky = 'nsew',rowspan=2)
filelist.config(border=2,relief = 'sunken')
for zone in os.listdir('/Windows/System32/drivers/'):#sample path
filelist.insert(tkinter.END,zone)
listscroll = tkinter.Scrollbar(mainwindow,orient = tkinter.VERTICAL,command = filelist.yview)
listscroll.grid(row = 1,column=1,sticky = 'nsw',rowspan=2)
filelist['yscrollcommand']=listscroll.set
optionframe = tkinter.LabelFrame(mainwindow,text = 'File Details')
optionframe.grid(row=1,column=2,sticky ='ne')
rbvalue = tkinter.IntVar()
rbvalue.set(3)#to set the default option for radiobutton
#radio Buttons
radio1= tkinter.Radiobutton(optionframe,text = 'FileName',value =1,variable =rbvalue)
radio2= tkinter.Radiobutton(optionframe,text = 'Path',value =2,variable =rbvalue)
radio3= tkinter.Radiobutton(optionframe,text = 'TimeStamp',value =3,variable =rbvalue)
radio1.grid(row=0,column=0,sticky ='w')
radio2.grid(row=1,column=0,sticky ='w')
radio3.grid(row=2,column=0,sticky ='w')
#widget to display the result
resultLabel = tkinter.Label(mainwindow,text ="Result")
resultLabel.grid(row=2,column=2,sticky='nw')
result = tkinter.Entry(mainwindow)
result.grid(row=2,column=2,sticky='sw')
#Frame for Time Spinners
timeFrame = tkinter.LabelFrame(mainwindow,text = 'Time')
timeFrame.grid(row=3,column=0,sticky = 'new')
#Time Spinners
hourSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,24)))
minuteSpinner = tkinter.Spinbox(timeFrame,width=2,from_=0,to=59)
secondSpinner = tkinter.Spinbox(timeFrame,width=2,values = tuple(range(0,60)))
hourSpinner.grid(row=0,column=0)
tkinter.Label(timeFrame,text=':').grid(row=0,column=1)
minuteSpinner.grid(row=0,column=2)
tkinter.Label(timeFrame,text=':').grid(row=0,column=3)
secondSpinner.grid(row=0,column=4)
timeFrame['padx']=36
#Frame for Date Spinners
dateFrame = tkinter.Frame(mainwindow)
dateFrame.grid(row=4,column=0,sticky = 'new')
#Date Labels
dayLabel = tkinter.Label(dateFrame,text='Day')
monthLabel = tkinter.Label(dateFrame,text='Month')
yearLabel = tkinter.Label(dateFrame,text='Year')
dayLabel.grid(row=0,column=0,sticky ='w')
monthLabel.grid(row=0,column=1,sticky ='w')
yearLabel.grid(row=0,column=2,sticky ='w')
#Date Spinners
daySpin = tkinter.Spinbox(dateFrame,width=5,from_=1,to=31)
monthSpin = tkinter.Spinbox(dateFrame,width=5,values=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"))
yearSpin = tkinter.Spinbox(dateFrame,width=5,from_=2000,to=2099)
daySpin.grid(row=1,column=0)
monthSpin.grid(row=1,column=1)
yearSpin.grid(row=1,column=2)
#buttons
okButton = tkinter.Button(mainwindow,text = 'OK')
cancelButton = tkinter.Button(mainwindow,text = 'Cancel',command = mainwindow.destroy)
okButton.grid(row=4,column=3,sticky='e')
cancelButton.grid(row=4,column=4,sticky='w')
mainwindow.mainloop()
print (rbvalue.get())#to confirm the selection of correct value in radio button
Tuesday, 13 March 2018
Python tkinter - Day 18(10 days later)
import tkinter
print(tkinter.TkVersion)
print(tkinter.TclVersion)
# tkinter._test()
# or we can use the below piece of code
mainWindowvar = tkinter.Tk()
mainWindowvar.title('test')
# mainWindow.geometry('2000x2000')
#below code will specify the screen size and position of the
#new window
mainWindowvar.geometry('400x400-5-10')
# # help(tkinter)
#
# labelvar = tkinter.Label(mainWindowvar,text = "this is label")
# labelvar.pack(side = "top")
#
# canvasvar = tkinter.Canvas(mainWindowvar, relief = 'raised',borderwidth=1)
# canvasvar.pack(side='left', anchor = 'n')
# button1 = tkinter.Button(mainWindowvar,text = "button1")
# button2 = tkinter.Button(mainWindowvar,text = "button2")
# button3 = tkinter.Button(mainWindowvar,text = "button3")
# button1.pack(side ='top')
# button2.pack(side ='top')
# button3.pack(side ='top')
#
# mainWindowvar.mainloop()
# help(tkinter)
#the above code will work but to make it proper we
#can introduce frame
labelvar = tkinter.Label(mainWindowvar,text = "this is label")
labelvar.pack(side = "top")
leftframevar = tkinter.Frame(mainWindowvar)
leftframevar.pack(side='left',anchor = 'n',fill=tkinter.Y,expand =False)
canvasvar = tkinter.Canvas(leftframevar, relief = 'raised',borderwidth=1)
canvasvar.pack(side='left', anchor = 'n')
rightframevar = tkinter.Frame(mainWindowvar)
rightframevar.pack(side='right',anchor = 'n',fill=tkinter.Y,expand =True)
button1 = tkinter.Button(rightframevar,text = "button1")
button2 = tkinter.Button(rightframevar,text = "button2")
button3 = tkinter.Button(rightframevar,text = "button3")
button1.pack(side ='top')
button2.pack(side ='top')
button3.pack(side ='top')
mainWindowvar.mainloop()
Subscribe to:
Posts (Atom)



