Build a color game using Tkinter in Python

You can program mini-games in Python in a very simple way. Here's how to create a color quiz game using Tkinter in Python.

Battlefield2, World of Tanks, The Sims4 and Freedom Force are just a few of the thousands of fascinating games programmed in Python.

Tkinter, the standard Python interface for the Tk GUI toolkit, is a powerful module that makes creating graphical user interfaces easy and fun. Using this module you can develop a Color Game - English quiz game about colors.

What is Color Game?

In Color Game, this program shows the name of a color on the screen but with a different font color. For example, it shows the word Yellow in red font color, the player must enter the correct color name of the text in the corresponding field.

Misinformation along with the stopwatch is a confounding factor and creates a highly entertaining gameplay experience.

Tkinter and Random . Modules

To build a Color Game, you will use the tkinter and random modules. Tkinter is a user-friendly, simple and cross-platform GUI module that you can use to create graphical user interfaces really fast.

It has some useful tools like label and entry widgets and layout managers like pack, grid and place. The functions provided are quite simple, so much so that even novice programmers can design the application without much effort. To install tkinter in the system, run the following command in the terminal:

pip install tkinter

The random module is a built-in library with which you can generate random selections. Using this module you can develop number guessing games, random password generators and much more.

How to create a color puzzle game in Python

Start by importing tkinter and the random module. Store the color's name as a list of strings and initialize the variable score to 0 and time_remaining to 60 .

from tkinter import * import random colours = ['Red', 'Green', 'Blue', 'Black', 'Pink', 'White', 'Purple', 'Yellow', 'Brown'] score = 0 time_remaining = 60

Define beginGame() function , which takes event as input argument. This function implements two tasks. First, it checks to see if time_remaining is equal to 60. If true, it calls and runs countdown(). Second, it calls the nextcolor() function , which shuffles randomly and displays the colors and scores while the game is running.

def beginGame(event):     if time_remaining == 60:         countdown()     nextColour()

Define a function nextColour() and reference the global variable. If the remaining time is greater than 0, set the target on the input field with focus_set() on the entry label (stored in the variable e ). It will be defined in the second half of the code.

Use the get() function to extract the current entry's text as a string and convert it to lowercase to avoid a mismatch. If this value is equal to the color shown on the screen, increase the score by one. Use the delete() function from 0 to the last index on the widget entry to clarify the content.

def nextColour():     global score     global time_remaining     if time_remaining > 0:         e.focus_set()         if e.get().lower() == colours[1].lower():             score += 1         e.delete(0, END)

Use the shuffle() function to rearrange the items in the list and show the color label with the text as the first color in this list and the font color as the second in the list. Use the config() function on the scoreLabel (requires pressing Enter ) to display the score when playing the game.

        random.shuffle(colours)         label.config(fg=str(colours[1]), text=str(colours[0]))         scoreLabel.config(text="Score: " + str(score))

Define a function called countdown() that references the remaining time and decrements it by 1. Use the config() function on the timeLabel to show the remaining screen time and the after() function to call the countdown function again after a delay of 1000 milliseconds or one second.

def countdown():     global time_remaining     if time_remaining > 0:         time_remaining -= 1         timeLabel.config(text="Time left: " + str(time_remaining))         timeLabel.after(1000, countdown)

Initialize the tkinter instance and show the root window. Set the title, pixel size, and background color of the window.

root = Tk() root.title("Color Game With a Twist") root.geometry("750x450") root.configure(background='Orange')

Use the Label widget to lead the player to the game guide. It accepts the main window in which you will place it. This text will show the font style and size along with the background color of the label. Use the pack() function to rearrange the label widget into blocks before placing them in the main widget.

Similarly, define the score label to instruct the user to press Enter to start the game, and the time label to show the remaining time. Make sure all the labels have a yellow-orange background color so they blend into the background. Define an empty label that will contain the color names in the nextColour() function .

instructions = Label(root, text="Type the colour of the word not the text ;)", font=('Arial', 24), bg="orange") instructions.pack() scoreLabel = Label(root, text="Press Enter to begin", font=('Arial', 24), bg="orange") scoreLabel.pack() timeLabel = Label(root, text="Time remaining: " + str(time_remaining), font=('Arial', 24), bg="orange") timeLabel.pack() label = Label(root, font=('Arial', 90), bg="orange")

As mentioned at the beginning, use widget entry to record player responses. An important step to remember is to bind the Enter key to an event in the tkinter window so that when the player presses it, the corresponding function will be implemented.

To get that result, you pass the key and beginGame() as parameters to the bind() function . Alternatively, use pack() and focus_set() to align and set focus on the input field label when you press Enter .

e = Entry(font=20) root.bind('', beginGame) e.pack() e.focus_set()

The mainloop() function tells Python to run the tkinter event loop and listen for action until you close this window.

root.mainloop()

Put all the code together and you've got a fun Color Game for everyone to enjoy.

When running the Color Game program, a window appears on the screen. When pressing Enter, the countdown timer runs, the player must start typing the exact color name of the word that appears. For each correct answer, you will get one point. When the game is over, the total score will appear on the screen.

Build a color game using Tkinter in Python Picture 1Build a color game using Tkinter in Python Picture 1

Above is how to create games in Python. Hope the article is useful to you.

5 ★ | 1 Vote