CREATE A GUI WITH TKINTER
WHAT IS TKINTER
Tkinter is a Python library designed to help you build a GUI (Graphical User Interface). By adding to your program Windows, Menu's, Icon and use of Pointers your program becomes much more user friendly, interesting and more fun than a simple text based program.
GETTING STARTED - IMPORTING TKINTER
Before you start creating a GUI with Tkinter you need to check if that platform you use to program in Python will run Python GUIs and the tkinter module. The standard Python Idle runs Tkinter with no additional changes needed. Through other Python editors such as Sublime Text you may have to run your code via the 'Command Prompt' (PC) or Terminal (MAC). To test if Tkinter works, type ' import tkinter' and run the program, you should not get any error messages.
NOTE: Some styling methods in tkinter do not work as good on a MAC as they do on a Windows or Linux machine. If you are working on a MAC and you think you code is correct but the style is not appearing then it could be because of the MAC OS.
NOTE: Some styling methods in tkinter do not work as good on a MAC as they do on a Windows or Linux machine. If you are working on a MAC and you think you code is correct but the style is not appearing then it could be because of the MAC OS.
VIDEOS IN THIS SECTION
CREATING WINDOWS
Creating a new window with Tkinter is easy, you can specify a fixed size, minimum size or maximum size of the window and you can create multiple windows. The code below creates an empty window and gives it the title of 'MY GUI'. The word 'screen' is just a variable so you can call it anything you like. Please feel free to copy and try the code.
By adding the following line of code you can also give the background colour:
screen.configure(background="#710071")
Note you can use hexadecimal colour codes or simply write the name of the colour. For example.
screen.configure(background="Blue")
screen.configure(background="#710071")
Note you can use hexadecimal colour codes or simply write the name of the colour. For example.
screen.configure(background="Blue")
It is easy to create more than one widow. In the 'Basic Window' example we create one window called 'screen', you can simply repeat the same code but give new windows you create a different name, for example 'screen2'. See the example in the code below.
Using the same principle as creating multiple windows you can create a pop-up window. The below code give an example of this being used.
You can use the canvas method to divide your screen into sections. This mades it easy to organise your page and if need be remove the content of an entire section, for example you might want the header of a page to stage the same on all pages but the body section to change between pages, using the canvas method would allow you to destroy all items in the body section but keep the header section.
The code below show creating 4 canvas and placing an item of text in one canvas, the variable zone1, zone2, zone3 and zone 4 have been used to distinguish between each canvas
The code below show creating 4 canvas and placing an item of text in one canvas, the variable zone1, zone2, zone3 and zone 4 have been used to distinguish between each canvas
This section demonstrates how to split your screen up into various Frames, very much like the canvas method it is very useful to separate sections of your GUI.
Want a hexadecimal colour chart? CLICK HERE
PLACING OBJECTS
This is probably the most popular method to use when placing items on the screen. It allows you to choose the coordinates where you want to place your item.
The code above uses 2 different ways to place the text, to place 'Hello World', relx and rely have been used to place the text in relation to the screen or frame it is placed in, you will notice if the window size is changed then the text will move relative to the anchor point given. the text 'Keep calm and code' is in a fixed position on the screen by using the X and Y coordinates, this will not move if the screen/window size is adjusted. Copy the code and try it.
The grid method is more versatile than the pack method however you may still prefer to use the 'place' method shown in the next section. If you are willing to spend some time to plan out your project and then use a loop to create a complete grid template of your screen then the grid method can be a good method to use when placing items on the screen.
In this example code it demonstrates that even if you place on item a few columns away from another, unless you have created the empty grids in-between the items then they will be placed right next to each other on the screen.
This issue can be fixed with a little cheat method by creating an empty grid first and then placing the items in the grid in the desired position as demonstrated in the code below.
This issue can be fixed with a little cheat method by creating an empty grid first and then placing the items in the grid in the desired position as demonstrated in the code below.
You can see from the code above that empty columns and rows are created to create a complete grid of the screen. It is now easier to put items anywhere on the screen. You create and place in just 1 line of code for example:
myText = Label(screen, text = "Hello World").grid(row = 1, column = 1)
myText = Label(screen, text = "Hello World").grid(row = 1, column = 1)
The pack method is an easy method to use however it does have its limitations compared to the 'place' method. Although you should learn the pack method you will probably find yourself using the palace method more often.
The pack method will simply place the item in the next space on the screen.
The pack method will simply place the item in the next space on the screen.
myText = Label(screen, text = "Hello World") ​myText.pack()
Notice with the code that you fist need to create the item, for example the variable myText and its content. After you have created the item you then need to tell Python what to do with the item, in this case pack it on the screen.
Note: you do not need to use 2 lines you could create and pack on the same line of code for example.
myText = Label(screen, text = "Hello World") .pack()
Other methods to yous with pack()
SIDE - Where to pack the item within the window: TOP, BOTTOM, LEFT, RIGHT
FILL - If you want the item to fill the allocated space: X (Vertical), Y(Horizontal), BOTH, NONE
EXPAND - The item will expand to fill extra space not used: TRUE, FALSE
Example: myText = Label(screen, text = "Hello World") .pack(side = RIGHT)
Note: you do not need to use 2 lines you could create and pack on the same line of code for example.
myText = Label(screen, text = "Hello World") .pack()
Other methods to yous with pack()
SIDE - Where to pack the item within the window: TOP, BOTTOM, LEFT, RIGHT
FILL - If you want the item to fill the allocated space: X (Vertical), Y(Horizontal), BOTH, NONE
EXPAND - The item will expand to fill extra space not used: TRUE, FALSE
Example: myText = Label(screen, text = "Hello World") .pack(side = RIGHT)
LABELS
A label, commonly referred to as a text box is easy to place on the screen. First you create the label and then you place it on the screen, although this can be done in one line of code the example below shows the creation of a label using the Label method (Note: Label is case sensitive). The nameLabel is just a variable so you can call this anything. On the next line the label is placed on the screen.
FONT STYLES
ADDING IMAGES
NOTE: Firstly make sure you save your images in the same file location that your Python file is saved, this will mean you will not have to tell Python where the images can be located. Secondly make sure you image is a suitable file type such as png or gif.
The code below shows an easy way of inserting an image without needing to use any additional library.
The code below shows an easy way of inserting an image without needing to use any additional library.
If you want to do more than just open your image, for example resize, rotate or change the quality then using Pillow is a good option. First you may need to install PILLOW to do this:
Go to the 'Command Prompt' or 'Terminal'
Type: pip3 install pillow
You should see the library being installed. To use Pillow to import an image in python follow the code below.
Go to the 'Command Prompt' or 'Terminal'
Type: pip3 install pillow
You should see the library being installed. To use Pillow to import an image in python follow the code below.
Although you could to re-size the image in another program such as photoshop before using it in Python. The next method shows how to re-size the image using the PILLOW library.
If you have tried to put your image inside a function you may have noticed that it does not work as expected, this is because the photo method used the widget is a local variable. The code below shows 3 possible solutions to this problem.
BUTTONS
Adding buttons is quite easy as can be seen from the code below.
To add an action to your button the easy way is to create a function or procedure that you want to happen when the button is pressed. As you can see in the code below the 'command' method is used to call the function. The strange thing about calling functions from this command method is that you do not need to put the brackets () after the function name.
To add an action to your button the easy way is to create a function or procedure that you want to happen when the button is pressed. As you can see in the code below the 'command' method is used to call the function. The strange thing about calling functions from this command method is that you do not need to put the brackets () after the function name.
The example code below shows adding RAISED effect to a button, changing the text colour with fg and changing the text colour when the button is click with activeforeground. More button styling methods methods can be seen in the list below the example code. Remember some methods do not work as good on a MAC as they do on a Windows or Linux machine.
PASS ARGUMENTS/PARAMETERS ON BUTTON CLICK
You will notice that when you use a Button you will use the 'command =' to call your function, not only do you not use the brackets when calling the function but you cannot pass parameters into your function. To solve this problem you can use the lambda method. Simply add 'lambda:' before you call your function and you can then pass in your values. See an example used in the code below.
You will notice that when you use a Button you will use the 'command =' to call your function, not only do you not use the brackets when calling the function but you cannot pass parameters into your function. To solve this problem you can use the lambda method. Simply add 'lambda:' before you call your function and you can then pass in your values. See an example used in the code below.
You can use the same method to pass multiple values, in the example below two strings are passed, you can pass variables the same way. Remember you must also receive the passed values in the function brackets.
BUTTONS - ADVANCED
CREATE A BUTTON FROM USER INPUT
BIND MULTIPLE COMMANDS TO A BUTTON PRESS
ADDING USER INPUT AND SELECTION
Using the 'Entry' method you can add a box that the user can type in, you can then use the '.get' method to retrieve the content of the entry box.
The following code shows how to create dropdown option boxes, in this example one for Coffee and one for Tea. The choice the user makes is set to a function and saved int he variable 'drink'.
Note that a parameter is received in the option function even though it is not apparent that a value is sent in, this can be confusing.
Note that a parameter is received in the option function even though it is not apparent that a value is sent in, this can be confusing.
The following code demonstrates creating drop down menus for your screen. Functions have been set up to demonstrate each item clicked works. On a Windows machine the menu should appear on the Python tkinter Window, on a MAC the menu will appear on the computer menu bar.
Adding a list box is quite easy and the listbox will automatically scroll even without adding a scrollbar. The code below creates a list of 30 items and puts them into the listbox.
REMOVING ITEMS FROM THE SCREEN
Code Editor
REMOVE SELECTED ITEMS FROM THE SCREEN
The next section of code changes this method to destroy items specified in a list. As you can see if you run the code, only the two items in the list (welcome and confirmRemove) are removed.
The next section of code changes this method to destroy items specified in a list. As you can see if you run the code, only the two items in the list (welcome and confirmRemove) are removed.
REMOVE EVERYTHING FROM A SELECTED CANVAS
The final section of code below destroys all items in a specified location, in this case the canvas named zone1.
The final section of code below destroys all items in a specified location, in this case the canvas named zone1.
MORE TKINTER
This shows how using the .after method you can set a delay on an action. In this example the 'Welcome' message shows for 2 seconds then disappears.
This section shows how to play music, it uses the pygame module to play the music. First you will need to install pygame, to do this go to your 'Command Prompt' or 'Terminal' and type:
pip3 install pygame
pip3 install pygame
For a complete tutorial on creating a GUI MUSIC PLAYER CLICK HERE to visit the page that shows how to build a music player with Python and Tkinter.
Adding a scrollbar can be confusing and may take a little tweaking of your code to get it working how you expect. It is also worth noting that many objects such as listboxes will scroll even without a scroll bar.
The code below gives you an example of how to place a chart into a Tkinter window. Copy the code and try to change the size of the chart and background, you will notice the two lines that control the size are a little confusing, spend a bit of timing playing around with the values to get a clear understanding.
The code below create a pop-up window when the EXIT button is pressed, the window asks the user to confirm if they want to quit or cancel. This is done in 3 function as follows:
exitProgram() function simply exits the program
cancelExit() destroys the confirm exit window
confirmExit() creates the confirm exit window and content and using the lambda method sends the variable screen2 to the cancelExit function, this was done because screen2 was created inside the confirmExit function therefore cannot be seen inside the cancelExit function.
exitProgram() function simply exits the program
cancelExit() destroys the confirm exit window
confirmExit() creates the confirm exit window and content and using the lambda method sends the variable screen2 to the cancelExit function, this was done because screen2 was created inside the confirmExit function therefore cannot be seen inside the cancelExit function.
You might want to close the window and keep the program running or close a chosen window, you can do this using the destroy() method. In the example below the window named 'screen' is closed when the 'CLOSE WINDOW' button is pressed.
Code Editor
You can detect if the user presses a key by binding a keypress to a screen, object, frame or canvas. For example:
screen.bind('<Return>', kingbob)
Binds a press of the Return key to the screen and when the key is pressed it runs the function called kingbob.
NOTE: You are now passing an event so you need to remember to receive this in the function. In the example below you can see the event is received when calling the functions, for example: def jellyfish(event). This can be slightly confusing because you receive the event but do not need to explicitly send the event.
screen.bind('<Return>', kingbob)
Binds a press of the Return key to the screen and when the key is pressed it runs the function called kingbob.
NOTE: You are now passing an event so you need to remember to receive this in the function. In the example below you can see the event is received when calling the functions, for example: def jellyfish(event). This can be slightly confusing because you receive the event but do not need to explicitly send the event.
The code below expands on the above by making a new window open if the user presses the spacebar.