Как сделать так, чтобы при нажатии кнопки числа, значение этого числа было занесено в клетку поля. Python

При нажатии на кнопку числа программа должна задавать выбранной клетке поля значение данного числа. Но при нажатии на кнопку числа программа нечего не делает Код:

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
import socket

SIZE = 9
CELL_SIZE = 50
selected_cell = None

def send_data(data):
    server_address = ('localhost', 12345)
    str = ""
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect(server_address)
        client_socket.send(data.encode())
        response = client_socket.recv(1024).decode()
        str = response
        if str != "":
            process_response(response)
    except ConnectionRefusedError:
        messagebox.showinfo("Connection Error", "Connection refused. Make sure the server is running")
    finally:
        client_socket.close()
        return str

def process_response(response):
    messagebox.showinfo("Response: ", response)

def read_board_data(level):
    if level == "1":
        file_path = "D:\Унік\Visual Projects\Kursach_Sudoku\Easy_Mode\Board 1.txt"
    elif level == "2":
        file_path = "D:\Унік\Visual Projects\Kursach_Sudoku\Hard_Mode\Board 1.txt"
    else:
        return None

    try:
        with open(file_path, 'r') as file:
            lines = file.readlines()

        board_data = [[0] * SIZE for _ in range(SIZE)]
        for line in lines:
            values = line.strip().split()
            if len(values) == 3:
                row = int(values[0]) - 1
                col = int(values[1]) - 1
                value = int(values[2])
                if 0 <= row < SIZE and 0 <= col < SIZE:
                    board_data[row][col] = value

        return board_data
    except FileNotFoundError:
        return None

def hide_menu():
    title_label.grid_remove()
    menu_choice_label.grid_remove()
    start_button.grid_remove()
    statistics_button.grid_remove()
    rules_button.grid_remove()
    quit_button.grid_remove()

def hide_statistic():
    statistics_label.grid_remove()

def hide_rules():
    rules_label.grid_remove()

def hide_modes():
    easy_button.grid_remove()
    hard_button.grid_remove()

def show_menu():
    title_label.grid()
    menu_choice_label.grid()
    start_button.grid()
    statistics_button.grid()
    rules_button.grid()
    quit_button.grid(row=5, columnspan=2, pady=5)
    back_button.grid_remove()

def mode_choice():
    hide_menu()
    difficulty_frame = tk.Frame(menu_frame)
    difficulty_frame.grid(row=2, columnspan=2, pady=10)

    global easy_button, hard_button
    easy_button = tk.Button(difficulty_frame, text="Легкий рівень", width=20, command=lambda: start_game("1"))
    easy_button.grid(row=0, column=0, padx=5)

    hard_button = tk.Button(difficulty_frame, text="Важкий рівень", width=20, command=lambda: start_game("2"))
    hard_button.grid(row=1, column=0, padx=5)

    difficulty_frame.grid(row=2, column=1, pady=10)

    quit_button.grid(row=5, columnspan=2, pady=5)

def start_game(difficulty):
    global selected_cell
    selected_cell = None
    back_button.grid_remove()
    hide_modes()
    send_data(difficulty)
    board_data = read_board_data(difficulty)
    if board_data:
        generate_board(board_data)
    else:
        # Handle error reading board data
        print("Error reading board data.")

value_buttons = []
def generate_board(board_data):
    global selected_cell  # Declare selected_cell as global to modify its value

    def fill_cell(x, y):
        global selected_cell

        if selected_cell is not None:
            x1 = selected_cell[0] * CELL_SIZE
            y1 = selected_cell[1] * CELL_SIZE
            x2 = x1 + CELL_SIZE
            y2 = y1 + CELL_SIZE
            canvas.create_rectangle(x1, y1, x2, y2, fill="white", outline="black")
            selected_cell = None

        if board_data[y][x] != 0:
            return

        selected_cell = (x, y)
        x1 = x * CELL_SIZE
        y1 = y * CELL_SIZE
        x2 = x1 + CELL_SIZE
        y2 = y1 + CELL_SIZE
        canvas.create_rectangle(x1, y1, x2, y2, fill="#CCCCCC", outline="black")

    selected_cell = None
    def fill_cell_with_number(num):
        global selected_cell

        if selected_cell is None:
            return

        x, y = selected_cell
        canvas.delete("highlight")
        canvas.create_rectangle(x * CELL_SIZE, y * CELL_SIZE, (x + 1) * CELL_SIZE, (y + 1) * CELL_SIZE, fill="white", outline="black")

        if board_data[y][x] == 0:
            if num != 0:
                canvas.create_text((x * CELL_SIZE + CELL_SIZE / 2), (y * CELL_SIZE + CELL_SIZE / 2), text=num, fill="red", tags="number")
                board_data[y][x] = num
            else:
                canvas.delete("number")
                board_data[y][x] = 0

        selected_cell = None

    def show_number_buttons(event):
        global selected_cell

        if selected_cell:
            x = selected_cell[0]
            y = selected_cell[1]
            value_frame.grid(row=y + 1, column=x, pady=5)

    def hide_number_buttons(event):
        value_frame.grid_remove()

    def handle_click(event):
        x = event.x // CELL_SIZE
        y = event.y // CELL_SIZE
        fill_cell(x, y)

    def number_button_click(num):
        fill_cell_with_number(num)
        value_frame.grid_remove()

    def create_number_button(num):
        if num in set(sum(board_data, [])):
            value_button = tk.Button(buttons_frame, text=str(num), width=3, font=("Helvetica", 16))
        else:
            value_button = tk.Button(buttons_frame, text=str(num), width=3, font=("Helvetica", 16), command=lambda num=num: number_button_click(num))
        value_button.grid(row=0, column=num - 1, pady=2)
        value_buttons.append(value_button)

    selected_cell = None  # Initialize selected_cell to None

    board_frame = tk.Frame(menu_frame)
    board_frame.grid(row=2, columnspan=2, pady=10)

    buttons_frame = tk.Frame(menu_frame)
    buttons_frame.grid(row=3, columnspan=2, pady=10)

    value_frame = tk.Frame(board_frame)
    value_frame.grid(row=0, column=0)

    canvas = tk.Canvas(board_frame, width=SIZE * CELL_SIZE, height=SIZE * CELL_SIZE)
    canvas.grid(row=0, column=0)

    canvas.bind("<Button-1>", handle_click)
    canvas.bind("<Enter>", show_number_buttons)
    canvas.bind("<Leave>", hide_number_buttons)

    quit_button.grid(row=5, columnspan=SIZE, pady=5)

    for i in range(1, 10):
        create_number_button(i)

    for i in range(SIZE):
        for j in range(SIZE):
            cell_value = board_data[i][j]
            cell_color = "#D3D3D3" if cell_value != 0 else "white"
            x1 = j * CELL_SIZE
            y1 = i * CELL_SIZE
            x2 = x1 + CELL_SIZE
            y2 = y1 + CELL_SIZE

            canvas.create_rectangle(x1, y1, x2, y2, fill=cell_color, outline="black")

            if cell_value != 0:
                canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=cell_value, fill="red", font=("Helvetica", 20))

    quit_button.grid(row=5, columnspan=SIZE, pady=5)


def show_statistics():
    hide_menu()
    with open('D:\Унік\Visual Projects\Kursach_Sudoku\Statistic.txt', 'r', encoding='utf-8') as file:
        statistics = file.read()
    global statistics_label
    statistics_label = tk.Label(menu_frame, text=statistics, font=("Helvetica", 12), justify="left")
    statistics_label.grid(row=2, columnspan=SIZE, pady=10, sticky="nsew")

    back_button.grid(row=5, columnspan=SIZE, pady=5, sticky="w")

def show_rules():
    hide_menu()
    with open('D:\Унік\Visual Projects\Kursach_Sudoku\Rules.txt', 'r', encoding='utf-8') as file:
        rules = file.read()
    global rules_label
    rules_label = tk.Label(menu_frame, text=rules, font=("Helvetica", 12), justify="left", wraplength=400)
    rules_label.grid(row=2, columnspan=SIZE, pady=10, sticky="nsew")

    back_button.grid(row=5, columnspan=SIZE, pady=5, sticky="w")

def go_back():
    if 'board_frame' in globals():
        board_frame.destroy()
    if 'statistics_label' in globals() and statistics_label.winfo_ismapped():
        hide_statistic()
    elif 'rules_label' in globals() and rules_label.winfo_ismapped():
        hide_rules()
    else:
        hide_modes()
    show_menu()

def exit_game():
    root.destroy()

root = tk.Tk()
root.title("Гра судоку")

menu_frame = ttk.Frame(root)
menu_frame.pack(padx=20, pady=20)

title_label = tk.Label(menu_frame, text="Вітаємо вас у грі судоку", font=("Helvetica", 16, "bold"))
title_label.grid(row=0, columnspan=SIZE, pady=10, sticky="nsew")

menu_choice_label = tk.Label(menu_frame, text="Меню:", font=("Helvetica", 12))
menu_choice_label.grid(row=1, columnspan=SIZE, pady=10, sticky="nsew")

start_button = tk.Button(menu_frame, text="Початок гри", width=20, command=mode_choice)
start_button.grid(row=2, column=0, pady=5, sticky="nsew")

statistics_button = tk.Button(menu_frame, text="Статистика", width=20, command=show_statistics)
statistics_button.grid(row=3, column=0, pady=5, sticky="nsew")

rules_button = tk.Button(menu_frame, text="Правила", width=20, command=show_rules)
rules_button.grid(row=4, column=0, pady=5, sticky="nsew")

quit_button = tk.Button(menu_frame, text="Вихід", width=20, command=exit_game)
quit_button.grid(row=5, columnspan=SIZE, pady=5, sticky="nsew")

back_button = tk.Button(menu_frame, text="Назад", width=20, command=go_back)
back_button.grid(row=5, columnspan=SIZE, pady=5, sticky="w")
back_button.grid_remove()

show_menu()

root.mainloop()

Ответы (0 шт):