Cover Image for A Colour game using Tkinter in Python
253 views

A Colour game using Tkinter in Python

Creating a simple color game using Tkinter in Python can be a fun project. In this game, you’ll display a color name, and the player’s task is to click on a button with the corresponding color. Here’s a basic example to get you started:

Python
import tkinter as tk
import random

# Define a list of colors and their corresponding names
colors = {
    "red": "Red",
    "green": "Green",
    "blue": "Blue",
    "yellow": "Yellow",
    "orange": "Orange",
    "purple": "Purple",
}

# Create the main application window
root = tk.Tk()
root.title("Color Game")

# Create a label to display the color name
color_label = tk.Label(root, text="", font=("Arial", 24))
color_label.pack(pady=20)

# Function to start a new round of the game
def start_new_round():
    color_name, color_value = random.choice(list(colors.items()))
    color_label.config(text=color_value, fg=color_name)
    random.shuffle(list(colors.keys()))

# Create buttons for each color
button_frame = tk.Frame(root)
button_frame.pack(pady=10)

for color_name in colors.keys():
    color_button = tk.Button(button_frame, text=color_name, width=10, height=2, command=lambda name=color_name: check_color(name))
    color_button.pack(side=tk.LEFT, padx=10)

# Function to check if the clicked button matches the displayed color
def check_color(clicked_color):
    displayed_color = color_label.cget("fg")
    if clicked_color == displayed_color:
        result_label.config(text="Correct!", fg="green")
    else:
        result_label.config(text="Wrong!", fg="red")

# Create a label to display the game result
result_label = tk.Label(root, text="", font=("Arial", 18))
result_label.pack(pady=10)

# Start the first round of the game
start_new_round()

# Start the Tkinter main loop
root.mainloop()

In this code:

  • We create a simple color game with a list of colors and their corresponding names.
  • We use Tkinter to create a graphical user interface (GUI) for the game, including labels for color names, buttons for each color, and a result label.
  • The start_new_round function selects a random color from the list and displays its name with a corresponding color. It also shuffles the order of color buttons.
  • The check_color function is called when a color button is clicked. It compares the clicked color with the displayed color and updates the result label accordingly.
  • We start the first round of the game with start_new_round().
  • The game continues in a loop until the user closes the window.

This is a simple example, and you can expand it by adding more colors, increasing difficulty, or implementing a scoring system.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS