Напиши программу на Python которое создает клетчат...

Creato il: 12 luglio 2025

Risposto usando O3 da Chat01

Domanda

Напиши программу на Python которое создает клетчатое поле 30 на 30, причем так что на каждую клетку можно нажать и оно сменит цвет. Необходимо чтобы у клеток было минимум 3 цвета.

Pensiero

Creating clickable grid with Tkinter

The user is asking for a Python program that creates a clickable checkered grid of 30x30, with each cell cycling through at least three colors when clicked. Since no specific library was mentioned, Tkinter seems like a good choice for a GUI solution. Tkinter's canvas can handle drawing the grid, and with a straightforward click function, I can cycle through the colors for each cell. I'll go ahead and provide the code that accomplishes this.

Creating a clickable color-changing grid

The user requested a Python code for a 30x30 grid with color-changing cells. The basic idea is to use Tkinter for creating this clickable grid and cycling through 3 or more colors when clicked. I’ll use a dictionary to map cell IDs to color indexes and handle the click events to change the colors. I'll also include meaningful comments and instructions in the code. Here's the solution that should meet all the given specifications, ensuring clarity and functionality. I'll skip any unnecessary online research since Tkinter usage is stable.

Thought for 11 seconds

Risposta

Вот минимальный пример на Tkinter.
Запустите скрипт — появится окно с полем 30 × 30. Каждый клик по клетке переключает её цвет по кругу (белый → красный → синий → зелёный → снова белый).

python
import tkinter as tk ROWS = COLS = 30 # размеры поля CELL = 20 # размер клетки в пикселях COLORS = ["white", "red", "blue", "green"] # минимум 3 цвета def main(): root = tk.Tk() root.title("Клетчатое поле 30×30") canvas = tk.Canvas(root, width=COLS * CELL, height=ROWS * CELL, highlightthickness=0) canvas.pack() # словарь «id прямоугольника → индекс текущего цвета» color_idx = {} # рисуем сетку и заполняем словарь начальными цветами for r in range(ROWS): for c in range(COLS): x0 = c * CELL y0 = r * CELL x1 = x0 + CELL y1 = y0 + CELL rect_id = canvas.create_rectangle( x0, y0, x1, y1, fill=COLORS[0], outline="gray70") color_idx[rect_id] = 0 def on_click(event): # узнаём, по какому объекту кликнули items = canvas.find_withtag("current") if not items: return rect = items[0] # вычисляем следующий цвет idx = (color_idx[rect] + 1) % len(COLORS) color_idx[rect] = idx canvas.itemconfig(rect, fill=COLORS[idx]) canvas.bind("<Button-1>", on_click) root.mainloop() if __name__ == "__main__": main()

Как работает:

  1. Создаём Canvas нужного размера.
  2. Рисуем 900 прямоугольников-клеток и запоминаем их идентификаторы.
  3. В обработчике кликов берём текущую клетку ("current"), находим следующий цвет из списка COLORS и обновляем заливку.

При желании можно:

  • изменить список COLORS, чтобы добавить/убрать оттенки;
  • настроить размер клетки (CELL) или поля (ROWS, COLS);
  • заменить порядок переключения цветов.

Condividi questa Q&A