Coin Flip App in Python Tkinter – A Complete Guide

Filed Under: Python Modules
Coin Flip Python

In this tutorial, we will create a coin flip application using Python Tkinter. Tkinter is the standard GUI Python library that helps to make graphical-user-interface-based applications.

Also Read: Python Tkinter tutorial – part 1

Building the Coin Flip Application

For this program, we need Python NumPyPillow, and Tkinter libraries. If you don’t have the modules in your system, make sure you use the pip command in cmd.

pip install numpy
pip install pillow
pip install tk

Importing Modules

After installing the libraries we can start developing our application by importing all modules in our program.

import numpy as np
from tkinter import *
from PIL import Image, ImageTk

Creating the Basic window of the application

First, we’ll initialize the Tkinter class using Tk() object and assign it to the ‘app’ variable. In the second line of code, we specify the size of the application window using the geometry method.

Next, we will be assigning the background color of the application window using the config method and set the color as bg attribute. By default, you can resize the window and you can use the resizable method to make sure it remains of the same size.

app = Tk()
 
app.title("The Coin Flipper!")
app.geometry('300x300+50+50')
app.resizable(False, False)
app.configure(bg='#2ECC71')
 
app.mainloop()

After running the above code we will get the screen below.

The Coin Flip Output Screen 1
The Coin Flip Output Screen 1

Loading Images into the Program

In this step, we will be loading images of both the heads and tails side of a coin into our program. The images must be saved in the same directory as your code file to make sure the code works perfectly.

app = Tk()
 
app.title("The Coin Flipper!")
app.geometry('300x300+50+50')
app.resizable(False, False)
app.configure(bg='#2ECC71')

#Heads image
load = Image.open("Heads.png")
heads = ImageTk.PhotoImage(load)
#Tails image
load = Image.open("Tails.png")
tails = ImageTk.PhotoImage(load)

app.mainloop()

Adding Widgets to the Application Window

Now that our main window is ready, we will be adding widgets to the application.

First, we need to add the title of the application in form of a label widget. Next, we need a button that will Toss the coin whenever the user presses it. Along with this we will add a toss_coin function and add it as a command attribute in the button. We will complete the function in the later sections.

app = Tk()
 
app.title("The Coin Flipper!")
app.geometry('300x300+50+50')
app.resizable(False, False)
app.configure(bg='#2ECC71')

load = Image.open("Heads.png")
heads = ImageTk.PhotoImage(load)
load = Image.open("Tails.png")
tails = ImageTk.PhotoImage(load)

# Title of the Application
Title = Label(text="Welcome to The Coin Fliper!!",
              bg="black",fg="white",font=("Arial", 14)).pack()

# Button and Function to FLip the Coin
def toss_coin():
    pass

btn1=Button(text="Flip the Coin!!", font=("Arial", 10), command=toss_coin, 
            bg='black', fg='white', activebackground="red", 
            padx=10, pady=10)
btn1.pack()

app.mainloop()
The Coin Flip Output Screen 2
The Coin Flip Output Screen 2

Next, we need to add the image that will change on the button click. For the same, we will be adding a Label and setting it as the image. Now it’s up to you if you need the application to start off with the heads or tails. I start with the heads image.

app = Tk()
 
app.title("The Coin Flipper!")
app.geometry('300x300+50+50')
app.resizable(False, False)
app.configure(bg='#2ECC71')

load = Image.open("Heads.png")
heads = ImageTk.PhotoImage(load)
load = Image.open("Tails.png")
tails = ImageTk.PhotoImage(load)

Title = Label(text="Welcome to The Coin Fliper!!",
              bg="black",fg="white",font=("Arial", 14)).pack()

def toss_coin():
    pass

# Image as a Label
img = Label(image=heads)
img.pack()

btn1=Button(text="Flip the Coin!!", font=("Arial", 10), command=toss_coin, 
            bg='black', fg='white', activebackground="red", 
            padx=10, pady=10)
btn1.pack()


app.mainloop()
The Coin Flip Output Screen 3
The Coin Flip Output Screen 3

Implementing toss_coin() function

When we toss a coin, it has a 50% chance that it lands on either head or tail. To make sure we achieve that we will make use of the NumPy module. The random.binomial function will return either one or zero.

On the basis of the value we get, we will render either a heads or tails images. The code for the function is below.

def toss_coin():
    result = np.random.binomial(1,0.5)
    if(result == 1):
        i.config(image = heads)
         
    else:
        i.config(image = tails)

The Complete Code

The full code will look like this:

app = Tk()
 
app.title("The Coin Flipper!")
app.geometry('300x300+50+50')
app.resizable(False, False)
app.configure(bg='#2ECC71')

load = Image.open("Heads.png")
heads = ImageTk.PhotoImage(load)
load = Image.open("Tails.png")
tails = ImageTk.PhotoImage(load)

Title = Label(text="Welcome to The Coin Fliper!!",
              bg="black",fg="white",font=("Arial", 14)).pack()

def toss_coin():
    result = np.random.binomial(1,0.5)
    if(result == 1):
        img.config(image = heads)
         
    else:
        img.config(image = tails)

img = Label(image=heads)
img.pack()

btn1=Button(text="Flip the Coin!!", font=("Arial", 10), command=toss_coin, 
            bg='black', fg='white', activebackground="red", 
            padx=10, pady=10)
btn1.pack()


app.mainloop()

Sample Outputs

The Coin Flip Output Screen 4
The Coin Flip Output Screen 4
The Coin Flip Output Screen 5
The Coin Flip Output Screen 5

Also Read: How To Create A GUI Age Calculator in Python Tkinter

close
Generic selectors
Exact matches only
Search in title
Search in content