Upgrade PySimpleGUI Sudoku to Use Buttons

Posted by


In this tutorial, we will be upgrading a basic Sudoku game using PySimpleGUI by replacing the input fields with buttons for a more user-friendly interface. This upgrade will allow players to easily select a number from 1 to 9 to fill in the Sudoku board. We will keep the game logic the same but just improve the visual aspect of the game.

Before we get started, make sure you have PySimpleGUI installed. You can install it using pip by running the following command in your terminal:

pip install pysimplegui

Now, let’s start by creating a basic Sudoku game using PySimpleGUI. Here is the code for the basic Sudoku game:

import PySimpleGUI as sg

layout = [[sg.Input(size=(2, 1), justification='center') for _ in range(9)] for _ in range(9)]

window = sg.Window('Sudoku', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

window.close()

This code creates a 9×9 grid of input fields where players can enter numbers from 1 to 9. Now, let’s upgrade this game by replacing the input fields with buttons for a better user experience.

First, we need to replace the input fields with buttons. We will also create a callback function to handle the button clicks and update the Sudoku board with the selected number.

Here is the code for the upgraded Sudoku game using buttons:

import PySimpleGUI as sg

layout = [[sg.Button('', size=(2, 1), key=(i, j)) for j in range(9)] for i in range(9)]
window = sg.Window('Sudoku', layout)

def update_board(event, values, board):
    row, col = event
    if board[row][col] == 0:
        clicked_button = window[event]
        clicked_button.update(str(values[event]))
        board[row][col] = int(values[event])

board = [[0 for _ in range(9)] for _ in range(9)]

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    update_board(event, values, board)

window.close()

In this code, we have replaced the input fields with buttons and created a callback function update_board to handle the button clicks and update the Sudoku board with the selected number. The board is represented as a 2D list of integers where 0 represents an empty cell. When a button is clicked, the callback function updates the board with the selected number and updates the button text accordingly.

Now, you have an upgraded Sudoku game where players can easily select numbers from 1 to 9 using buttons. Feel free to further customize the game with features like a solve button, timer, or hints. Have fun playing and improving your Sudoku skills!

0 0 votes
Article Rating

Leave a Reply

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@lymancargill1720
5 hours ago

Great work mate!! I recommend using Promosm.! ! Lots of people are using it to promote their videos.

@xuli5398
5 hours ago

Please can you post your code?

2
0
Would love your thoughts, please comment.x
()
x