Skip to main content

How to make GUI dictionary in python

In application development, a dictionary is an application that helps us with the meaning of a word by simply typing the word in a provided input box and clicking a button.

Follow the steps below to get started.

1.  IMPORT THE NECESSARY MODULES AND LIBRARIES

To be able to develop this application successfully, we need to first of all import the Tkinter module as shown in the coloured text below. Note, Tkinter comes already embedded in most python IDEs like Jupyter Notebook and Pycharm so requires no special installation.

from tkinter import *

Then import MessageBox. MessageBox as the name sounds helps us to display messages as popup in the event of an error or success or whatever you wish in your code. The syntax for importing the MessageBox is shown below.

from tkinter import messagebox as MessageBox



2. CREATE AND FORMAT A WINDOW (CONTAINER) FOR THE PROJECT

window = Tk() 
window.geometry("535x360") 
window.title('Dictionary - StudySourceCodes')
window.config(bg='darkolivegreen')

In the code above, the function Tk() creates a window or container for our project and stores it in the variable window which can be given any name you wish. The window created is like a container that houses all the contents of our application. 
The .geometry() function helps us to set a dimension  for our the created window. Where 535 is the width and  360 is the height.
The function title() gives a title or name (Dictionary - StudySourceCodes) to our application.
The config() function helps us to add a colour to our window. Where bg stands for 'background' and can also be written instead of bg. (e.g. background='darkolivegreen'). The screenshots below show what your code and output will look like when executed. Notice the inclusion of mainloop() function, it tells our program to keep displaying the window until the window is manually closed by clicking the close button at the top of the display. So, this line of code MUST always come last in any code we wish to run else we will not be able to see the output of the code, as the code will run and close almost immediately (within a tiny fraction of a second...too fast for a human eye to detect).
                                                                 
                         Code


                                      

              Output
                  
3CREATE WIDGETS 

Widgets include but not limited to Label, Buttons, Entry and Text.

Label is used to display text or images. 
Button is used to create a button in our application.
Entry is a widget that allows us to give input to our program from the GUI.
Text widget allows us to display text from our program to the GUI.
Th code below shows how to create thesl above mentioned widgets. For detailed information on more interesting Tkinter widgets click here.

Label(window,text="My Dictionary",bg='darkolivegreen',fg='black',
      font="Arial 12 bold").grid(column=0,row=0)

Label(window,text='\nEnter a word you would like to look for the meaning:',bg='darkolivegreen',
     fg='black',font='Arial 12').grid(column=0,row=1)

word_entry = Entry(window,width=22,bd=3,fg='black',bg='white')
word_entry.grid(column=0,row=2,pady=3)

Button(window,text='SUBMIT',width=7,fg='black',bd=3,bg='darkolivegreen',command=action).grid(column=0,row=4)

Label(window,text='\nDefinition:',fg='black',bg='darkolivegreen',
      font='Arial 12').grid(column=0,row=5)

output = Text(window,width=65,height=6,bd=3,bg='white',fg='black')
output.grid(column=0,row=7)

Label(window,text='Click to exit',bg='darkolivegreen',fg='black',
      font='Arial 12').grid(column=0,row=9)

Button(window,text='EXIT',width=5,bd=3,bg='darkolivegreen',height=1,font='Arial 12',fg='black',
      command=exit).grid(column=0,row=10)


The syntax above creates a label in our project window or container window with text My Dictionary, background colour darkolivegreen foreground colour black, font style Arial, font size 12, and Bold text. 

The grid function grid() is used to set the position of the created label in our project window. Change the values of rows and/or columns to alter the position of the label. Column and row take only positive integers, and so would not take decimal numbers (e.g. 0.5, 2.3, -4.5,...) and negative numbers (e.g. -1, -30, -6.5,....). The default value (value when no value is provided) of column is 0, while that of row is any first empty (unoccupied) row.
pady is a grid geometry manager that is used to further adjust the vertical position of the widget, while padx which is also a grid geometry manager can be used to further adjust the horizontal position of the widget.

Notice that in the Result below the code produced no output instead it triggered an error 'Name 'action' is not defined' as we have not defined the functions assigned to the commands in the button widget syntax.

                                                           
                                                                     Code

Result



4. DEFINE BUTTON COMMANDS

Make sure each button command functions are defined before (preferably just after your create and format window syntax) the button widget syntax to avoid RunTime  errors like the one in the screenshot above. Check the code screenshots below for a guide. Without any errors, you output will look like the one in the screenshot below.

def action():
    text_value = word_entry.get() 
    output.delete(0.0,END)

    try:
        definition = my_dictionary[text_value.lower()]
    except:     
        definition = 'Oops! The word you entered does not exist in the dictionary. \nPlease try another.'
    output.insert(END,definition)


def exit():
    window.destroy()


.get() function gets or extracts whatever word (dictionary key) is typed in the entry box word_entry and stores it in the variable text_value.
.delete() function deletes whatever text that is in the Text widget (output).

definition = my_dictionary[text_value.lower()]  from the code above retrieves the value of the dictionary key stored in the variable text_value if it exists in the dictionary my_dictionary, and stores it to the variable definition.

definition = 'Oops! The word you entered does not exist in the dictionary. \nPlease try another.'
from the code above assigns the string "Oops! The word you entered does not exist in the dictionary. \nPlease try another word!" to the variable definition.

.insert() function inserts or displays whatever is in definition in the Text box output depending on how the code evaluates (with error except or without error try).
    
.destroy() function closes or terminates the program window when button exit is clicked.

                                                                           Code




Output
                             

Though at this point everything looks perfect, but just one thing is remaining which you would already have guessed. If you look closely in the output above, you will see that an error message was returned in the definition box telling us that 'The word we are looking for does not exist in the dictionary', and this because we have not created the python dictionary that will store the words and their meanings as we highlighted earlier above. Step number 5 below takes care of this.


5. CREATE A PYTHON DICTIONARY 

A dictionary is unordered collection that is arranged in key and value pairs. The keys and values are written in quotes, separated by colons, and enclosed in curly braces. Each pair of key and value is separated by a comma from the next one.

my_dictionary = {'love':'Strong feeling of affection for something or somebody.',
                 'physics':'physics is the study of matter in relation to energy.',
                'power':'Time rate of doing work.\nFormula = work/time\nUnit = Watt',
                'work':'Product of force and distance moved by force.\nFormula = force * distance\nUnit = Joules',
                'speed':'Time rate of change of distance.\nFormula = distance/time\nUnit = m/s',
                 'velocity':'Time rate of change of displacement.\nFormula = displacement/time\nUnit = m/s',
                 'tkinter':'A standard python library for creating GUI applications.'
                }


The above syntax creates a python dictionary which stores the words to be looked for in its keys and the meaning of the words in its values such that whenever the word (key) is passed through the entry widget, the meaning  (value) of the word is retrieved. Therefore, making the purpose of our application a success. To learn more about how to create and manipulate dictionaries in python click here. The screenshots below shows a replica of the code and the final output of the program.

When you look closely in the output below, you will see that this time the program returned the meaning of the word that was typed instead of an error as in the case above. This is because at this point a dictionary has been created which stores the words and their meanings, such that when our program tries to look up the typed word (dictionary key) in the dictionary my_dictionary created it finds it and returns the meaning of the word (dictionary value) as an output in the definition box.

                                                                        Code
                                     


                                                                           Final Output
               


6. MAIN.LOOP() FUNCTION

The mainloop() function is used to tell our system to keep running the program or displaying our window until it is manually closed by clicking the exit or close button. Without this line of code, our program will execute and display for a very tiny fraction of a second and closes. So always make sure it comes last at the end of any chunk of code you want to run. The syntax is shown below.

window.mainloop()   

If you had followed all the steps above correctly, your application should be up and running.

Do let us know in the comment box below if you encounter any challenges building the app and we will be glad to help.

How to make a simple GUI calculator in Python - TKinter

Comments