Make a GUI Magic 8 Ball App with Python and Tkinter

Hi Welcome to this new tutorial from MOO ICT. In this tutorial we will be making a small magic 8 ball style application using python and tkinter. This is a continuation tutorial on our Python Tutorial Series. For this application we will making this step by step in the video tutorial below. Before we start please make sure you have the PILLOW framework installed on your python. This framework allows us to use the ImageTk and Images function to load and display images to the Tkinter window.

We wanted to make this app while exploring how to use images dynamically using tkinter and os framework from python. We will dynamically load the images from a specific folder because there is 15 answer images available and instead of writing and defining them one by one we can load them all to a list and use that list show an answer to the user.

Lesson Objective –

  1. Make a Magic 8 Ball APP using python and Tkinter
  2. Create functions and events and link them to the button and the entry box
  3. Use various colours on the GUI in tkinter
  4. Use OS library to loop through a folder and load the images to a list
  5. Use lists and random to choose a random answer for the user input
  6. Check user input and show error message if the entry box is empty
  7. Bind Click button and Enter Key Event for the application

 

Video Tutorial –

 

Download the Magic 8 Ball Images Here

 

Source Code –

 

from tkinter import *
from tkinter import messagebox
import os
import random
from PIL import ImageTk, Image

root = Tk()
root.title("MOO ICT Magic 8 Ball App")
root.geometry("610x510")

# variables
magic_8_ball_images = []
folder_dir = "8ball_images"

#loop, events and functions
for images in os.listdir(folder_dir):
    if images.endswith(".jpg"):
        image = ImageTk.PhotoImage(Image.open(folder_dir+"/"+images).resize((400,350)))
        magic_8_ball_images.append(image)

print("total imaage avilable: ", len(magic_8_ball_images))
# end of the loop

# Created by MOO ICT 2022
# For educational purpose only

# Adding the event

def AskQuestion(event):
    if len(inputBox.get()) == 0:
        messagebox.showinfo("MOO Says: ", " Enter a Question First ")
    else: 
        ShowAnswer()

def ShowAnswer():
    num = random.randint(0, len(magic_8_ball_images) - 1)
    image_label.config(image=magic_8_ball_images[num])
    inputBox.delete(0, "end")


#GUI components
image_label = Label(root, image=magic_8_ball_images[4])
inputBox = Entry(root, width=30, font=("Arial 18 bold"), fg="maroon", bg="yellow", justify="center")
click_button = Button(root, text="Ask the Question", font=("Arial 20 bold"), bg="plum")

# pack the GUI
image_label.pack()
inputBox.pack(pady=10)
click_button.pack(side="bottom", pady=30)


click_button.bind("<Button-1>", AskQuestion)
inputBox.bind("<Return>", AskQuestion)

root.mainloop()

 

 

 




Comment on this tutorial and let us know how you got on -