Python | Scrabble Helper (tkinter)

By Casper_x | Python Programs | 7 Mar 2023


Tkinter Scrabble helper

 

Boost your Scrabble game with our Python Scrabble Helper! Utilizing the power of ‘tkinter’ for an easy-to-use graphical interface, our program generates word suggestions to help you score more points and beat your opponents.

This post is an upgrade version of Scrabble Helper asked by @Yahoomvx.

In this version of Scrabble Helper, I have only added a graphical user interface (GUI) with ‘tkinter’ library for ease of use during your games of Scrabble.

 

    What is ‘Tkinter’ ?

 

Tkinter is a standard Python library for creating user graphical interfaces (GUI). Tkinter is a built-in module in Python that uses the Tk graphics library to create user interfaces. Tkinter provides GUI widgets (such as buttons, labels, input fields, menus, etc.) that can be used to create applications with a graphical user interface.

 

    Prerequisites :

 

You need a text file named ‘words.txt' that contains a list of all valid Scrabble words from 2 to 7 letters long, separated by spaces. You can create this file yourself, or download one from a reputable source online.

You need to import ‘tkinter’ module

import tkinter as tk

    Program :

 

As we saw in the Scrabble Helper post , you need to create a function called 'categorize_words' that takes 2 arguments, a list of words and a list of letters. The function uses these two arguments to categorize the words based on their length and suitability to the available letters.

def categorize_words(words, letters):

    categorized_words = {i: [] for i in range(2, 8)}

 

    for word in words:

        length = len(word)

        if length >= 2 and length <= 7:

            word_is_valid = True

            for letter in word:

                if word.count(letter) > letters.count(letter):

                    word_is_valid = False

                    break

            if word_is_valid:

                categorized_words[length].append(word)

 

    return categorized_words

 

This second function is a main function ‘main()' that is called when the program is executed. 

The function reads a word file (words.txt), retrieves the words into a list, and then asks the user to input a string of letters. It uses the list of words and the letters inputted by the user to categorize the words based on their length and suitability to the available letters.

As before, the first step of the function is to open the 'words.txt' file and read the lines of the file. The lines are then processed to extract the words they contain. The extracted words are added to a list called 'words'.

Next, the function asks the user to input a string of letters using a tkinter widget 'input_entry'. This string of letters is converted to uppercase and stored in the variable 'letters'. (My 'words.txt' file is a list of capitalized words.)

The function then uses the list of words 'words' and the string of letters inputted by the user to call the function 'categorize_words' which categorizes the words based on their length and suitability to the available letters. The categorized words are stored in a dictionary called ’categorized_words’.

 

def main():

    with open(‘words.txt') as f:

        lines = f.readlines()

        words = []

        for line in lines:

            line_worlds = line.strip().split(" ")

            words += line_worlds

    letters = input_entry.get()

    letters = letters.upper()

    # print(‘Letters entered by the user : ‘, letters)

 

    categorized_words = categorize_words(words, letters)

 

Next, you will add this function to remove all child widgets of the ‘result_frame' widget. This allows resetting the ‘result_frame’ widget every time the function is called.

 

    for widget in result_frame.winfo_children():

        widget.destroy()

 

Lastly, the function iterates over each element of the 'categorized_words' dictionary to display the categorized words in the graphical interface. For each element in the dictionary, the function creates a tkinter 'Label' widget to display the number of letters of the words in that category. The function also creates another 'Label' widget to display the list of words in that category.

 

    for length, word_list in categorized_words.items():

        label = tk.Label(result_frame, text=f"Mots de {length} lettres :", font=(‘Helvetica', 14, ‘bold'))

        label.pack(pady=10)

        words = tk.Label(result_frame, text=word_list)

        words.pack()

 

Your ‘main( ):’ function should be like this :

 

def main():

    with open("words.txt") as f:

        lines = f.readlines()

        words = []

        for line in lines:

            line_worlds = line.strip().split(" ")

            words += line_worlds

    letters = input_entry.get()

    letters = letters.upper()

    print("Letters entered by the user : ", letters)

 

    categorized_words = categorize_words(words, letters)

 

    for widget in result_frame.winfo_children():

        widget.destroy()

 

    for length, word_list in categorized_words.items():

        label = tk.Label(result_frame, text=f"Mots de {length} lettres :", font=(‘Helvetica', 14, ‘bold'))

        label.pack(pady=10)

        words = tk.Label(result_frame, text=word_list)

        words.pack()

On that, we will define 2 event functions, the 'validate' and 'quit' functions.

The 'validate' function is called when the user clicks on the 'Validate' button. It calls the 'main' function to generate the list of words from the letters inputted by the user.

 

def validate():

    main()

 

The 'quit' function is called when the user clicks on the 'Quit' button. It stops the program by calling 'root.quit()' and displays the message "End of the program!" in the console.

 

def quit():

    root.quit()

    print("End of the program !")

    root.destroy()

 

These functions are used to define the actions to be taken when the user interacts with the graphical interface of the application.

 

Now, you will create the graphical interface using 'tkinter'.

You will start by creating an instance of the 'Tk' class from tkinter and store it in a variable named 'root'.

Set the size of the main window in pixels, '1000x500' for my example, and also set the title of the main window.

 

root = tk.Tk()

root.geometry(‘1000x500’)

root.title(‘Tkinter Scrabble Helper | By Casper_ X’)

 

The following lines create an input frame for the user, which contains a label 'Enter your 7 letters:', an entry field for entering the letters, and two buttons 'Validate' and 'Quit'.

The two buttons are configured to trigger the functions 'validate' and 'quit' respectively when clicked.

 

input_frame = tk.Frame(root)

input_frame.pack(pady=20)

 

label = tk.Label(input_frame, text=‘Input your 7 letters :’)

label.pack(side=’left')

 

input_entry = tk.Entry(input_frame, width=30)

input_entry.pack(side=‘left')

 

validate_button = tk.Button(input_frame, text=‘Validate', command=validate)

validate_button.pack(side=‘left’, padx=10)

 

quit_button = tk.Button(input_frame, text=‘Quit', command=quit)

quit_button.pack(side=‘right', padx=10)

 

 

Another frame is created to display the results.

 

result_frame = tk.Frame(root)

result_frame.pack()

 

Finally, the 'mainloop()' method is called to run the GUI and wait for the user to interact with it.

 

root.mainloop()

 

Finally, the ‘Scrabble Helper’ Python script is a powerful tool for any Scrabble player looking to improve their game. You can use the script to find the best words to play and gain an edge over your opponents. So why not give it a try today and see how it can help you dominate the Scrabble board!

 


As always, the complete code is at the end of the publication.

Thank you and congratulations to all those who didn't give up on reading this post.

Leave a comment if you have any questions

 

If you enjoy my blog posts, you can support me.

Thanks for you support 🙏

 

BTC : bc1qvfmetg2d36mmntrg56ld0tdrte8cqeygjxdpsg

ETH  | USDC | USDT : 0x02AbfBf22fA72d068Ff305e58dF782e58F863274

DOGE : DLtGbPrFvwW5y7jFuvuDAkZGNB2eAErAxA

 

See you soon ! 🤙

Casper_X 👻

 

Want more program ?

 

Take a look of these posts.

Scrabble Helper : https://www.publish0x.com/python-scrabble-helper/python-scrabble-helper-xvmqykg

QRcode generator : https://www.publish0x.com/python-scrabble-helper/python-qr-code-generator-xrgmxnx

Face detectionhttps://www.publish0x.com/python-scrabble-helper/python-face-detection-xjrwygy

Password generatorhttps://www.publish0x.com/python-scrabble-helper/python-password-generator-xyezmel

Caesar Cipher : https://www.publish0x.com/python-scrabble-helper/python-caesar-cipher-xvmqnex

 

Here is the full program :

 

import tkinter as tk



def categorize_words(words, letters):
    categorized_words = {i: [] for i in range(2, 8)}

    for word in words:
        length = len(word)
        if length >= 2 and length <= 7:
            word_is_valid = True
            for letter in word:
                if word.count(letter) > letters.count(letter):
                    word_is_valid = False
                    break
            if word_is_valid:
                categorized_words[length].append(word)

    return categorized_words


def main():
    with open(‘words.txt') as f:
        lines = f.readlines()
        words = []
        for line in lines:
            line_worlds = line.strip().split(" ")
            words += line_worlds
    letters = input_entry.get()
    letters = letters.upper()
    print(‘Letters entered by the user : ‘, letters)

    categorized_words = categorize_words(words, letters)

    for widget in result_frame.winfo_children():
        widget.destroy()

    for length, word_list in categorized_words.items():
        label = tk.Label(result_frame, text=f"Mots de {length} lettres :", font=(‘Helvetica', 14, ‘bold'))
        label.pack(pady=10)
        words = tk.Label(result_frame, text=word_list)
        words.pack()


def validate():
    main()


def quit():
    root.quit()
    print("End of the program !")
    root.destroy()


root = tk.Tk()
root.geometry(‘1000x500’)
root.title('Tkinter Scrabble Helper | By Casper_ X’)

input_frame = tk.Frame(root)
input_frame.pack(pady=20)

label = tk.Label(input_frame, text='Input your 7 letters :’)
label.pack(side=‘left')

input_entry = tk.Entry(input_frame, width=30)
input_entry.pack(side=‘left’)

validate_button = tk.Button(input_frame, text=‘Validate’, command=validate)
validate_button.pack(side=’left', padx=10)

quit_button = tk.Button(input_frame, text=‘Quit', command=quit)
quit_button.pack(side=‘right', padx=10)

result_frame = tk.Frame(root)
result_frame.pack()

root.mainloop()


How do you rate this article?

3


Casper_x
Casper_x

Python | Crypto | Javascript | Programming


Python Programs
Python Programs

Tutorials on the programming language 'Python'. In this blog you will find several basics Python programs to complete. Hope you enjoy the content !

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.