Fundamentals 44 min read

Seven Python Mini Projects with Source Code (Calculator, Notepad, Login, Snake, Tetris, Link Game)

This article presents seven beginner‑friendly Python mini‑projects—including a graphical calculator, a notepad editor, a login/registration interface, a Snake game, a Tetris clone, and a Link‑Match puzzle—each explained with design ideas, implementation steps, and complete source code using Tkinter or Pygame.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Seven Python Mini Projects with Source Code (Calculator, Notepad, Login, Snake, Tetris, Link Game)

The article introduces a collection of simple yet educational Python projects aimed at beginners who want to practice GUI programming and game development. Each project is described with its purpose, key concepts, and a full source code listing.

1. Calculator

A graphical calculator built with Tkinter that supports basic arithmetic operations, memory functions, and additional features such as square root and sign change. The implementation demonstrates Tkinter widget layout, event handling, and expression evaluation using eval.

def __init__(self):
    self.map = {(x, y): 0 for x in range(32) for y in range(24)}
    self.body = [[100, 100], [120, 100], [140, 100]]
    self.head = [140, 100]
    self.food = []
    self.food_color = []
    self.moving_direction = 'right'
    self.speed = 4
    self.generate_food()
    self.game_started = False

# ... (rest of the calculator implementation, including layout, button callbacks, and main loop)

2. Notepad

A basic text editor using Tkinter that supports creating, opening, saving files, as well as edit operations like cut, copy, paste, undo, redo, and find. It showcases menu creation, keyboard shortcuts, and file dialogs.

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
import os

filename = ""

def author():
    showinfo(title='作者', message='Python')

def power():
    showinfo(title='版权信息', message='课堂练习')

def mynew():
    global top, filename, textPad
    top.title('未命名文件')
    filename = None
    textPad.delete(1.0, END)

# ... (rest of the notepad implementation, including menu setup and event bindings)

3. Login and Registration

A user authentication interface built with Tkinter that demonstrates the use of entry widgets, buttons, and the pickle module for persisting user credentials. The example covers basic input validation and data serialization.

# Example snippet for login window
import tkinter as tk
import pickle

class LoginApp:
    def __init__(self, master):
        self.master = master
        self.master.title('登录')
        # ... (widgets for username, password, login button)

    def login(self):
        # Load user data with pickle and verify credentials
        pass

# ... (rest of the login/registration implementation)

4. Snake Game

A classic Snake game implemented with Pygame. The code explains screen setup, game loop, snake movement logic, food generation, collision detection, and scoring. It also includes optional sound effects.

import pygame
from os import path
from sys import exit
from time import sleep
from random import choice
from itertools import product
from pygame.locals import QUIT, KEYDOWN

def direction_check(moving_direction, change_direction):
    directions = [['up', 'down'], ['left', 'right']]
    if moving_direction in directions[0] and change_direction in directions[1]:
        return change_direction
    elif moving_direction in directions[1] and change_direction in directions[0]:
        return change_direction
    return moving_direction

class Snake:
    colors = list(product([0, 64, 128, 192, 255], repeat=3))[1:-1]
    def __init__(self):
        self.map = {(x, y): 0 for x in range(32) for y in range(24)}
        self.body = [[100, 100], [120, 100], [140, 100]]
        self.head = [140, 100]
        self.food = []
        self.food_color = []
        self.moving_direction = 'right'
        self.speed = 4
        self.generate_food()
        self.game_started = False

    # ... (additional methods for movement, food generation, and game logic)

def main():
    fps_clock = pygame.time.Clock()
    pygame.init()
    pygame.mixer.init()
    snake = Snake()
    # ... (event handling, drawing, and game loop)

if __name__ == '__main__':
    main()

5. Tetris

A full‑featured Tetris clone using Pygame. The implementation defines block shapes, rotation logic, line clearing, scoring, and rendering of the game board. It demonstrates use of data structures to manage the grid and piece placement.

import pygame
import random
import os

GRID_WIDTH = 20
GRID_NUM_WIDTH = 15
GRID_NUM_HEIGHT = 25
WIDTH, HEIGHT = GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT
SIDE_WIDTH = 200
SCREEN_WIDTH = WIDTH + SIDE_WIDTH
WHITE = (0xff, 0xff, 0xff)
BLACK = (0, 0, 0)
LINE_COLOR = (0x33, 0x33, 0x33)

CUBE_COLORS = [
    (0xcc, 0x99, 0x99), (0xff, 0xff, 0x99), (0x66, 0x66, 0x99),
    (0x99, 0x00, 0x66), (0xff, 0xcc, 0x00), (0xcc, 0x00, 0x33),
    (0xff, 0x00, 0x33), (0x00, 0x66, 0x99), (0xff, 0xff, 0x33),
    (0x99, 0x00, 0x33), (0xcc, 0xff, 0x66), (0xff, 0x99, 0x00)
]

screen = pygame.display.set_mode((SCREEN_WIDTH, HEIGHT))
pygame.display.set_caption('俄罗斯方块')
clock = pygame.time.Clock()
FPS = 30

score = 0
level = 1

screen_color_matrix = [[None] * GRID_NUM_WIDTH for _ in range(GRID_NUM_HEIGHT)]

class CubeShape(object):
    SHAPES = ['I', 'J', 'L', 'O', 'S', 'T', 'Z']
    # ... (shape definitions and rotation logic)
    def __init__(self):
        self.shape = random.choice(self.SHAPES)
        self.center = (2, GRID_NUM_WIDTH // 2)
        self.dir = random.randint(0, len(self.SHAPES_WITH_DIR[self.shape]) - 1)
        self.color = random.choice(CUBE_COLORS)

    # ... (methods for movement, rotation, drawing, and collision detection)

def draw_grids():
    for i in range(GRID_NUM_WIDTH):
        pygame.draw.line(screen, LINE_COLOR, (i * GRID_WIDTH, 0), (i * GRID_WIDTH, HEIGHT))
    for i in range(GRID_NUM_HEIGHT):
        pygame.draw.line(screen, LINE_COLOR, (0, i * GRID_WIDTH), (WIDTH, i * GRID_WIDTH))
    pygame.draw.line(screen, WHITE, (GRID_WIDTH * GRID_NUM_WIDTH, 0), (GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT))

# ... (functions for drawing matrix, score, line removal, and main game loop)

6. Link‑Match Puzzle

A classic "Link‑Match" (连连看) game built with Tkinter. The code creates a grid of paired images, handles mouse clicks to select tiles, checks connectivity with up to two bends, draws connecting lines, and removes matched pairs. It includes algorithms for direct line, one‑corner, and two‑corner connections.

from tkinter import *
from tkinter.messagebox import *
from threading import Timer
import time
import random

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def IsLink(p1, p2):
    if lineCheck(p1, p2):
        return True
    if OneCornerLink(p1, p2):
        return True
    if TwoCornerLink(p1, p2):
        return True
    return False

# ... (functions IsSame, lineCheck, OneCornerLink, TwoCornerLink, drawLinkLine, undrawConnectLine, etc.)

def callback(event):
    global Select_first, p1, p2, firstSelectRectId, SecondSelectRectId
    x = event.x // 40
    y = event.y // 40
    if map[x][y] == " ":
        showinfo(title='提示', message='此处无方块')
    else:
        if not Select_first:
            p1 = Point(x, y)
            firstSelectRectId = cv.create_rectangle(x*40, y*40, x*40+40, y*40+40, width=2, outline='blue')
            Select_first = True
        else:
            p2 = Point(x, y)
            if p1.x == p2.x and p1.y == p2.y:
                return
            SecondSelectRectId = cv.create_rectangle(x*40, y*40, x*40+40, y*40+40, width=2, outline='yellow')
            if IsSame(p1, p2) and IsLink(p1, p2):
                drawLinkLine(p1, p2)
                t = Timer(timer_interval, delayrun)
                t.start()
            else:
                cv.delete(firstSelectRectId)
                cv.delete(SecondSelectRectId)
                Select_first = False

# ... (rest of the game setup, map generation, UI binding, and mainloop)

Overall, the article serves as a practical tutorial collection for Python beginners, covering GUI development with Tkinter and simple game creation with Pygame, and provides ready‑to‑run source code for each example.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GUIPythonGame DevelopmentTutorialTkinter
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.