Download Python tkinter file for beginners and more Assignments Artificial Intelligence in PDF only on Docsity!
Python GUI Programming using Tkinter
In this lesson, we will learn how to develop graphical user interfaces by writing some Python GUI
examples using Tkinter package. Tkinter package is shipped with Python as a standard package, so we
don’t need to install anything to use it.
Tkinter package is a very powerful package. If you already have installed Python, you may use IDLE
which is the integrated IDE that is shipped with Python, this IDE is written using Tkinter. Sounds Cool!!
We will use Python 3.7, so if you are using Python 2.x, it’s strongly recommended to switch to Python
3.x unless you know the language changes so you can adjust the code to run without errors.
We will start by creating a window then we will learn how to add widgets such as buttons, combo boxes,
etc, then we will play with their properties, so let’s get started.
Create your first GUI application
First, we will import Tkinter package and create a window and set its title:
The last line which calls mainloop function, this function calls the endless loop of the window, so the
window will wait for any user interaction till we close it. If you forget to call the mainloop function,
nothing will appear to the user.
Create a label widget
To add a label to our previous example, we will create a label using the label class like this:
lbl = Label(win, text="Hello")
Then we will set its position on the form using the grid function and give it the location like this:
lbl.grid(column= 0 , row= 0 )
So, the complete code will be like this:
Without calling the grid function for the label, it won’t show up.
Change button foreground and background colors
You can change foreground for a button or any other widget using fg property. Also, you can change the
background color for any widget using bg property.
Now, if you tried to click on the button, nothing happens because the click event of the button isn’t
written yet.
Handle button click event
First, we will write the function that we need to execute when the button is clicked:
def clicked(): lbl.configure(text="Button was clicked !!")
Then we will wire it with the button by specifying the function like this:
btn = Button(win, text= “Click Me” , command=clicked)
Note that , we typed clicked only not clicked() with parentheses.
Get input using Entry class (Tkinter textbox)
In the previous Python GUI examples, we saw how to add simple widgets, now let’s try getting the user
input using Tkinter Entry class (Tkinter textbox).
You can create a textbox using Tkinter Entry class like this:
txt = Entry(window,width= 10 )
Then you can add it to the window using grid function as usual So, our window will be like this:
def clicked():
res = "Welcome to " + txt.get()
lbl.configure(text= res)
Set focus to entry widget
That’s super easy, all we need to do is to call focus function like this:
txt.focus()
Add a combobox widget
To add a combobox widget, you can use the Combobox class from ttk library like this:
from tkinter.ttk import * combo = Combobox(win)
Then you can add your values to the combobox.
As you can see, we add the combobox items using the tuple. To set the selected item, you can pass the
index of the desired item to the current function.
To get the select item, you can use the get function like this:
combo.get()
Add a Checkbutton widget (Tkinter checkbox)
To create a checkbutton widget, you can use Checkbutton class like this:
chk = Checkbutton(window, text='Choose')
Also, you can set the checked state by passing the check value to the Checkbutton like this:
Set check state of a Checkbutton
Here we create a variable of type BooleanVar which is not a standard Python variable, it’s a Tkinter
variable, and then we pass it to the Checkbutton class to set the check state as the highlighted line in the
above example. You can set the Boolean value to false to make it unchecked. Also, you can use IntVar
instead of BooleanVar and set the value to 0 or 1.
Add radio buttons widgets
To add radio buttons, simply you can use RadioButton class like this:
rad1 = Radiobutton(window,text='First', value=1)
Note that you should set the value for every radio button with a different value , otherwise, they won’t
work.
Also, you can set the command of any of these radio buttons to a specific function, so if the user clicks
on any one of them, it runs the function code. Every time you select a radio button, the value of the
variable will be changed to the value of the selected radio button.
Add a ScrolledText widget (Tkinter textarea)
To add a ScrolledText widget, you can use the ScrolledText class like this:
from tkinter import scrolledtext
txt = scrolledtext.ScrolledText(window,width=40,height=10)
Here we specify the width and the height of the ScrolledText widget, otherwise, it will fill the entire
window.
Show warning and error messages
You can show a warning message or error message the same way. The only thing that needs to be
changed is the message function
messagebox.showwarning('Message title', 'Message content') messagebox.showerror('Message title', 'Message content') Show askquestion dialogs
To show a yes, no message box to the user, you can use one of the following messagebox functions:
You can choose the appropriate message style according to your needs. Just replace the showinfo
function line from the previous line and run it. Also, you can check what button was clicked using the
result variable. If you click OK or yes or retry , it will return True value, but if you choose no or
cancel , it will return False. The only function that returns one of three values is askyesnocancel
function, it returns True or False or None.
Add a SpinBox (numbers widget)
To create a Spinbox widget, you can use Spinbox class like this:
spin = Spinbox(window, from_= 0 , to= 100 )
Here we create a Spinbox widget and we pass the from_ and to parameters to specify the numbers range
for the Spinbox. Also, you can specify the width of the widget using the width parameter:
spin = Spinbox(window, from_= 0 , to= 100 , width= 5 )
You can specify the numbers for the Spinbox instead of using the whole range like this:
spin = Spinbox(window, values=( 3 , 8 , 11 ), width= 5 )
Here the Spinbox widget only shows these 3 numbers only 3, 8 and 11.
Set default value for Spinbox
To set the Spinbox default value, you can pass the value to the textvariable parameter like this:
var =IntVar()
var.set(4) spin = Spinbox(window, from_=0, to=100, width=5, textvariable=var)
Now, if you run the program, it will show 4 as a default value for the Spinbox.
Add a Menu bar
To add a menu bar, you can use menu class like this:
from tkinter import Menu menu = Menu(window) menu.add_command(label='File') window.config(menu=menu)
First, we create a menu, then we add our first label, and finally, we assign the menu to our window.
You can add menu items under any menu by using add_cascade() function like this:
menu.add_cascade(label='File', menu=new_item)
Here we add another menu item called Edit with a menu separator. You may notice a dashed line at the
beginning, well, if you click that line, it will show the menu items in a small separate window. You can
disable this feature by disabling the tearoff feature like this:
new_item = Menu(menu, tearoff= 0 )
Just replace the new_item in the above example with this one and it won’t show the dashed line
anymore. I don’t need to remind you that you can type any code that works when the user clicks on any
menu item by specifying the command property.
new_item.add_command(label='New', command=clicked) Add a Notebook widget (tab control)
To create a tab control, there are 4 steps to do so.
First, we create a tab control using Notebook class
Create a tab using Frame class.
Add that tab to the tab control.
Pack the tab control so it becomes visible in the window.
Add widgets to Notebooks
After creating tabs, you can put widgets inside these tabs by assigning the parent property to the desired
tab.