Category: Python Tkinter

What is Tkinter?

What is Tkinter?

Hello everyone, in this module we will discuss about What is Tkinter? You may hear about Tkinter. So the question arises that what is Tkinter and why it is necessary.

What is Tkinter
What is Tkinter

Python provides us various options to crate GUI(Graphical User interfaces), tkinter is one of them. In simple words we can define tkinter is:

  • Tkinter stands for ‘Tkinter Interface’
  • It is standard python library to interface with Tk GUI toolkit
  • Tkinter is written in python.
  • It is most widely used for developing python GUI Applications
  • Tkinter is an fast and easy way to developing interactive user interfaces
  • As it is provide interface with Tk GUI toolkit, so it support various widgets like entry, buttons etc.
  • In python 2.0 it was known as ‘Tkinter’, but in python 3.0 it renamed as ‘tkinter’
  • Now it consist with standard Linux, Microsoft Windows and Mac OS X installs of Python

To understand Tkinter deeply, first of all we need to understand about TCL.

What is Tcl/tk and how Tkinter Introduced?

TCL stands for True Command Language.It is general-purpose, high-level, interpreted, dynamic programming language. It is very easy and powerful language. Here are some important points about TCL:

  • It was first introduced in 1988 by John Ousterhout.
  • Like python it support multiple programming paradigms like Object Oriented Programming, Procedural Oriented Programming etc.
  • It is an cross platform language that allows to run TCL on wide variety of systems.
  • It is common application is embedded system, i.e. it can be run on other language independently.
  • Furthermore, it combine with Tk extension, this combination is known as Tcl/Tk
  • This combination allows us to build Graphical User Interfaces natively in TCL.
  • So now Tcl/Tk comes with installation of python i.e. known as Tkinter.

Why need Tkinter?

As we know that python is an server side language, which runs on command line. So sometimes the application developed in python, proves less interactive to the user. Because the application we develop in python runs on black screen or command line. So, to make them more interactive we needs an Graphical User Interface rather than Command Line Interface. Here is the way how the aystem layer interacts:

What is Tkinter
What is Tkinter : layers

As you can see in the image above, Tkinter has an interface with Python and Tcl/tk. Here is the detailed explanation of above image:

  • First of all here is an Hardware layer, which interfaces with OS.
  • Tcl/tk is responsible to actually creates multiple widgets like Entry box, button etc.
  • As we know that TCL is an another language, so to use it in python we need an interface.
  • This interface is Tkinter, which we can say that call to Tcl/tk and enable python application to add widgets.

How Tkinter works | Tkinter first window

To create an GUI with python, we need to do is:

  1. Call to Tkinter i.e. import tkinter library
  2. Create an Tkinter window
  3. Apply widgets on that window
  4. Apply events on the widgets to perform actions
  5. Call to infinite loop, which is responsible to show the main window.

Example

from tkinter import * #in python 2.0 its "Tkinter"

#Create Main Window
main_window = Tk()

#Add Title on Window
main_window.title("First Window")

#Add Widgets
Label(main_window,text="Welcome to First Window",fg='red',bg='yellow').pack()   

#Show main_window

Output

What is Tkinter
What is Tkinter

So it is all about today’s tutorial, to learn more widgets and geometry managers of Tkinter visit the link below:

pack()

Tkinter Scrollbar

Tkinter Scrollbar

Tkinter scrollbar is an standard python widget used to create a scrollbar on tkinter window. As we know that when there is a bulk of content to display i.e. out of screen size or overflow. In this case, to let entire content show, we need to scroll it down. You can see scrollbars at every window, phone etc.

Now the question is that how to create these scrollbars. As we use tkinter to build desktop applications, here it is more necessary to learn about making scrollbars. Let’s discuss about Tkinter Scrollbar!!!

Syntax

Here is the syntax for creating a scrollbar in tkinter:

obj = Scrollbar(main_window, other_options)

main_window

It is the root or we can say parent window , which holds tall the widgets . We have to pass this window  as a parameter to the Scrollbar() function . Passing the main_window as a parameter denotes that , Scrollbar() is a child of it .

other_parameters

There are number of other options that we can provide to a Scrollbar() widget . These can be for style , layout , size etc. of the Scrollbar widget .

Types of Scrollbars

Here are two types of tkinter Scrollbars:

  1. Horizontal Scrollbar(relative to x-axis)
  2. Vertical Scrollbar(relative to y-axis)

Steps to create a scrollbar

To make any task easy, the best approach is to break it in number of small steps. And do it step by step. Specially in programming, first of all break your task into small steps, trust me it will make so easy to complete it. So here is the steps for creating a scrollbar in tkinter:

    1. Create an widget on which you want to apply scrollbar
    2. Furthermore, create an scrollbar widget
    3. In order to connect the scrollbar to the widget, we need to do:
    4. Set the widget’s yscrollcommand callbacks to the set method of the scrollbar  widget and
    5. Set the scrollbar’s command attribute to the yview method of the widget

Example

from tkinter import *
root = Tk()
root.title("Scrollbar Widget")
#ITEMS
list = ["Shirt","Bag","Toy","Books","Fruits",
        "Vegetables","Jeans","Headphones",
        "Watch","Dress","Snaks","Dry fruits",
        'Mobile','Headphones','Shoes']
#Function CALls on Button Click
def add():
    w = Lb.get(ACTIVE)
    cart.insert(END,w)
    Scr.set(10,400)
    print("Item {} Added to Your Cart".format(w))

#Item Listbox
Lb = Listbox(root)
Lb.pack(side=LEFT, expand=1,fill=X)

cart = Listbox(root)
cart.pack(side=RIGHT, expand=1,fill=X)

# TKINTER SCROLLBAR
Scr = Scrollbar(root,troughcolor='red',jump=1,width=32)
Scr.pack(side=LEFT,fill=Y)

Btn= Button(root,text="ADD TO CART ->",fg='white',bg='green',command=add).pack(side=RIGHT)
for i in list:
    Lb.insert(END ,i)

#CONFIG SCROLLBAR WITH WIDGET
Lb.config(yscrollcommand=Scr.set)
Scr.config(command=Lb.yview)

# OUTPUT SCREEN
mainloop()

Output:

Tkinter Scrollbar
Tkinter Scrollbar

Explanation:

  • First of all i have created a list of items and add items to the Listbox widget using the for loop.
  • There is also an button, which calls a function named add() on click.
  • add() function adds the active item to the second Listbox widget.
  • As you can see here, there are various items in the first listbox widget i.e. overflows the screen.
  • In this case to make all visible, we need a vertical scrollbar here.
  • So, i have created a scrollbar object Scr, after that configure this scrollbar to the Listbox widget.
  • By default the width of the scrollbar is 16px, but we can alter it using width attribute. (In example i have set width to 32px)
  • You may also note that, i have set(10,400) on button click, which is responsible for changing the size of the scrollbar slider.

Horizontal scrollbar

As you can see in the example, here is an vertical scrollbar, which moves the window along to the Y-axis i.e. top to down. But in some cases like Message boxes, Images , there is also requirement to move window horizontally.

In this case, we use horizontal scrollbar, which moves the window along the X-axis i.e. left to right. Adding a horizontal scrollbar is very simple. Just use the xscrollcommand option instead of yscrollcommand , and the xview method instead of  ysview  method.

Download Source Code :

So, it is all about Tkinter Scrollbar. To download the entire source code you can click on button below. Stay connected to learn more about Django and python. Good Luck!!!

Django AJAX
Tkinter Scrollbar

 

 

Tkinter Scale

Tkinter Scale

Tkinter Scale widget is an standard python widget to draw a scale on tkinter window . We can then use this scale widget as an measurement tool in our desktop applications . We can create an scale with any range and difference . Basically a Tkinter Scale is an graphical slider on the tkinter window from which we can select any value . We can create horizontal as well as vertical scale .

tkinter scale
tkinter scale

Here is the syntax for the scale widget in Tkinter :

Syntax

Scale(main_window , other_parameters)

main_window

It is the root or we can say parent window , which holds the other widgets . In Tkinter scale we have to pass this window  as a parameter to the scale() function . Passing the main_window as a parameter denotes that , scale() is a child of it .

other_parameters

There are number of other options that we can provide to a scale() widget . These can be for style , layout , size etc. of the scale() widget .

Example

Here are the two , horizontal and vertical scales :

from tkinter import *

master = Tk()

def values():
    l.delete(0,END)
    c1=var.get()
    c2=var2.get()
    for i in range(c1,c2+1):
        l.insert(END,i)
    lb = Label(master,text="Scale 1= {}".format(c1),fg='red',font="(cursive,20)").grid(row=2,column=2)
    lb2 = Label(master,text="Scale 2= {}".format(c2),fg='red',font="(cursive,20)").grid(row=3,column=2)

var = IntVar()
w = Scale(master, from_=1, to=50,resolution=1,activebackground='red',length=200, variable= var)
w.grid(row=0,column=0)

l= Listbox(master, width=20)
l.grid(row=0,column=1)

var2 = IntVar()
e = Scale(master, from_=1,resolution=2, to=100, orient=HORIZONTAL,sliderlength=15,length=150,variable=var2)
e.grid(row=1,column=1 , columnspan=4)

btn = Button(text="Get values",bg='green' ,fg='white', command=values).grid(row=3,column=0,columnspan=4)
mainloop()

Output:

Tkinter Scale Example
Tkinter Scale Example

Explanation

  • In above example , there are two scale widgets .
  • Also a Listbox and button.
  • We also can customize scale widget , according to us . Like in example there is a given range, from and to in which we need scale measurement .
  • Set orient attribute to HORIZONTAL, if you want horizontal scale widget .
  • Here is also an function associated with Button widget to create a listbox in selected range .

 

Tkinter Radiobutton

Tkinter Radiobutton

Tkinter Radiobutton is an standard tkinter widget . It is mostly used to select one option from multiple choices unlike checkboxes . We can select more than one options from a group of options in checkboxes . We uses radiobutton for a single choice . For example to select a gender .

These buttons can contain text or images. A button can only display text in single font . But you can write text in multiple lines using \n or other methods . A group of radiobutton contains a variable with same name ( to relate them ) but the value of each radio button may different.

We also can set command for each button . A command is an function which calls automatically on button click . We can get the selected value using get() method of button instance .

Syntax:

instance = Radiobutton( main_window , other_options )

main_window

It is the root or we can say parent window , which holds the other widgets . In Tkinter radiobutton we have to pass this window  as a parameter to the Radiobutton() function . Passing the main_window as a parameter denotes that , Radiobutton() is a child of it .

other_parameters

There are number of other options that we can provide to a Radiobutton() widget . These can be for style , layout , size etc. of the Radiobutton widget .

Example

Let’s take an simple example of , how Tkinter Radiobutton actually works . In the example below , here are two group of radiobuttons . Each Each group has four  Tkinter Radiobuttons .

from tkinter import *
from tkinter import messagebox
main = Tk()
main.title("Quiz")
def res():
    a= c.get()
    b= d.get()
    messagebox.showinfo("Result","""1. Selected Option:{}\t Correct Option: 4\n
    2. Selected Option:{} \tCorrect Option: 2""".format(a,b))
var = StringVar()
Ques= Label(main, textvariable=var , fg='red')
var.set("1. OS computer abbreviation usually means ?")
Ques.pack()

c=StringVar()
op1 = Radiobutton(main,text ="Optical Software",variable=c ,value=1).pack()
op2 = Radiobutton(main,text ="Open Software",variable=c ,value=2).pack()
op3 = Radiobutton(main,text ="Open Source",variable=c ,value=3).pack()
op4 = Radiobutton(main,text ="Operating System",variable=c ,value=4).pack()

var2 = StringVar()
Ques2= Label(main, textvariable=var2 , fg='red')
var2.set("2. 'DB' computer abbreviation usually means ?")
Ques2.pack()
d=StringVar()
op1 = Radiobutton(main,text ="Disk Block",variable=d ,value=1).pack()
op2 = Radiobutton(main,text ="Database",variable=d ,value=2).pack()
op3 = Radiobutton(main,text ="Data Binding",variable=d ,value=3).pack()
op4 = Radiobutton(main,text ="Disk Break",variable=d ,value=4).pack()

btn = Button(main,text="Submit",bg='green',fg='white', width=50,command=res)
btn.pack()

main.mainloop()

Output

Tkinter Radiobutton
Tkinter Radiobutton

Explanation

  • In above example there are two groups of radiobuttons.
  • Each group has four radiobuttons .
  • To make single selection from multiple selections ,add variable attribute with same value to Radiobutton() .
  • You can see there is attribute value with different values to define each button uniquely .
  • There is also an submit button with command add()  which calls automatically on button click .
  • Function add()  , gets value of each radiobutton and then check values accordingly and return an messagebox .

 

Tkinter Messagebox

Tkinter Messagebox

Tkinter Messagebox is a standard tkinter widget to show plain text on tkinter window. We also can use Label widget instead of Tkinter Messagebox .  To add message box in tkinter window, we uses Message()  method. It can be used to add multiple lines of text in tkinter window with single font . If you want to add multiple fonts in Tkinter Mesagebox you can use Text widget of Tkinter window .

Syntax

Messagebox( main_window , other_parameters )

– main_window

The main_window is the tkinter’s main window , there can only single main / parent window . All other widgets are placed in the main_window .

– other_parameters

There are various other options for layout , placement and style of the Tkinter Message including bg , height , font  etc.

Example – Decision maker using Tkinter Messagebox

from tkinter import *
import random
master = Tk()
master.geometry("400x300")

def decision():
    x= random.randint(0,1000)
    y= random.randint(0,1000)
    if x >=y:
        text.set("Yes !!!")
        m.config(bg="green")
    else:
        text.set("No !!!")
        m.config(bg="red")
lb = Label(text='Decision Maker' ,font=('cursive',30), fg='red' ).pack()
en = Entry(master, fg='orange', width=50,font=('cursive',15))
en.pack(ipady=20, pady=10, padx=2)
bt = Button(master, text='Check', width=50,bg='red',command=decision,fg='white')
bt.pack(ipady=7)
text = StringVar()
m = Message(textvariable=text,fg="white",font=('cursive',20))
m.pack(pady=20,ipadx=50)
mainloop()

Output

Tkinter Messagebox
Tkinter Messagebox

Explanation

  • In above code , i have create a Tkinter Messagebox , which displays result of the decision .
  • It is not an perfect decision maker , it is just for fun to let you know the working of Message() widget .
  • Here i have generate two random numbers x and y . ‘
  • Decision is depending upon the comparision values of these two numbers .
  • Also i have use config() method of Message() widget , which is responsible to set background color of Tkinter Messagebox .
  • config() is associates with the decision() function which calls every-time button clicked.

Tkinter messagebox other options

Sr No.

Parameter

Explanation

1
anchor
It is for the positioning of the text/image inside the Message widget i.e. where it should be placed . Possible values are NNEESESSWWNW, or CENTER. Default value is CENTER
2
bg
Allows us to change the background of Tkinter Message widget.
3
aspect ratio
It is the relationship between the height and width of the Messagebox() widget . It’s default value is 150 . If we set width , then aspect ratio will overwrite .
4
bd
To set the width(size) of the border we can use bd . Border denotes the boundary of the widget .
5

 

cursor
It allows us to set type of cursor for the Message widget . The defined cursor will show on mouse over to label widget . Possible values are dot , circle etc. and default value is arrow .
6
fg
Sets the color of the text on Message widget
7
font
It is the type of font to be use in Message text .Tkinter Message() allows us the text only in single font .
8
justify
We can use justify attribute to set the alignment of multiple lines of the text . Possible values are LEFT, RIGHT and default value is CENTER .
9
padx
It allows us to add horizontal (left-right) space around the text and the border of the widget. Its default value is 1px .
10
pady
It allows us to add vertical ( top-bottom ) space around the text and the border of the widget. Its default value is 1px .
11
relief
Allows us to set the type of border . Possible values are SUNKENRAISEDGROOVE, and RIDGE and default value is FLAT .
12
text
It is the plain text to be display in the Message widget . Messagebox widget can automatically add new lines , to get required aspect ratio .
13
textvariable
It denotes the text to be display on the widget . It is used for dynamic text .

Default type is string .

14
width
It is the width of the label widget . If label contains text then it is in number of text units  . Else if label contains image its value depend on the number of pixels . The default value is according to the content .

So , it is all about the Tkinter Messagebox , Thanks!!!

Tkinter menu

Tkinter menu

Tkinter menu allows us to add options to our application . For this purpose , we can use standard Tkinter widget named Menu() . It has various menu types including pop-ups , pull-downs and top-levels.

Tkinter menu allows us to add different kind of options including commands , radio-buttons , checkbox etc. These options makes our application more scalable and usable. We also can cascade various options into single options .

In our previous tutorial , we have discussed the Tkinter Menubutton and basics of Tkinter menu . If you wan’t to learn about these topics , you can visit the link below :

Tkinter Menubutton

Syntax

Menu(main_window , other_parameters)

– main_window

The main_window is the tkinter’s main window , there can only single main / parent window . All other widgets are placed in the main_window .

– other_parameters

There are various other options for layout , placement and style of the Tkinter Menu including bg , height , font  etc.

Example – Creating Simple Tkinter menu

from tkinter import *
root = Tk()
root.title("My Text Editor")

# Text box in main window
l = Text(root)
l.pack()
#Parent Menu Container / root
menubar = Menu(root)

# TOP MENUS
menubar.add_cascade(label="File")
menubar.add_cascade(label="Edit")
menubar.add_cascade(label="Format")
menubar.add_cascade(label="View")
menubar.add_cascade(label="Help")

root.config(menu=menubar)
root.geometry("500x300")
root.mainloop()

Output

When executes the above code it will produce output as below :

Tkinter menu
Tkinter menu

Explanation

  • IN above code , there is one tkinter Menu() named menubar .
  • There are also various options to that menubar.
  • Also we have use add_cascade() method of it , to make these options parent of another options .
  • There is also Text() widget associated with root window .
  • You can write anything you want in Text-box .
  • In further example we will add its child options .

Example – Adding options to tkinter menu

In above example , we have created an Tkinter menu with cascading options . Now we will add child options to these parent options . Here is the code for doing the same :

from tkinter import *
root = Tk()
root.title("My Text Editor")

# Tkinter Text Widget to root window
l = Text(root)
l.pack()

#Tkinter Menu() / parent
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)

# TOP MENUS
menubar.add_cascade(label="File", menu=filemenu)
menubar.add_cascade(label="Edit")
menubar.add_cascade(label="Format")
menubar.add_cascade(label="View")
menubar.add_cascade(label="Help")

#Adding Options to File
filemenu.add_command(label="New")
filemenu.add_command(label="Open...")
filemenu.add_command(label="Save")
filemenu.add_command(label="Save As...")
filemenu.add_separator()
u = Menu(menubar, tearoff=0)
filemenu.add_cascade(label="Close", menu=u)
u.add_command(label="Tab")
u.add_command(label="Pane")
u.add_command(label="Window")
filemenu.add_command(label="Exit" , command = exit)

root.config(menu=menubar)
root.geometry("500x300")
root.mainloop()

Output

Here is the output of above code :

Tkinter menu
Tkinter menu

Explanation

  • As you can see in the above code , we can add option inside option .
  • There we have add menu inside menubar.
  • By default , tkinter adds a dotted line before options , setting tearoff = 0 removes this line .
  • You can cascade options at any label you want .
  • To add command with the option , you can use command attribute of add_command() method .
  • In above code , i have added python’s inbuilt command exit to option exit .

Tkinter menu – other parameters

Sr No.

Parameter

Explanation

1
bg
Allows us to change the background of Tkinter menu widget.
2
bd
To set the width(size) of the border we can use bd . Border denotes the boundary of the widget .
3
cursor
It allows us to set type of cursor for the menu widget . The defined cursor will show on mouse over to label widget . Possible values are dot , circle etc. and default value is arrow .
4
fg
Sets the color of the text on menu widget
5
postcommand
The menu instance may call function without any parameter . We can associate this function with menu instances’s postcommand attribute . It allows us to create dynamic applications .
6
font
It is the type of font to be use  .Tkinter menu allows us the text only in single font .
7
relief
Allows us to set the type of border . Possible values are SUNKENRAISEDGROOVE, and RIDGE and default value is FLAT .
8
tearoff
By default tkinter menu shows a tearoff  entry. It is a horizontal line , shows at first position. It returns a copy of other menu options in a separate TopLevel window . Set tearoff = 0 to remove it .
9

title

It is the main title of tearoff entry window . Default value is menu’s parent option . To change the title of tear-off window you can set it to any string.

(See output below)

Tkinter menu title example

If you wan’t to see the working of title attribute of tkinter’s menu . Add title attribute to Menu’s instance as shown below:

filemenu = Menu(menubar, title="Hello")

Output

Tkinter menu
Tkinter menu

So , its all about the Tkinter menu widget . I hope you guys understand , Thanks !!!

tkinter menubutton

Tkinter menubutton

To create a Tkinter menubutton we use a standard widget called Menubutton() . Menubutton() adds a simple button in tkinter window . It is associated with Tkinter Menu() widget to display options on the window . It always stays in the window .  After that we can add multiple options for that button . When user clicks on Menubutton() , these options appear . After that we can add functions ( actions ) to these options .

Syntax

– To create Menubutton

variable = Menubutton(main, other_parameters)

– To add options

variable.menu = Menu(mb)
variable.menu.add_command(label = 'option 1' , command = something )

Example – Create tkinter Menubutton with options

from tkinter import *

main = Tk()
main.config(bg="white")
main.geometry("200x200")

mb = Menubutton(main , text = "Menu", relief = RAISED )
mb.pack()
mb.menu = Menu(mb)
mb["menu"] = mb.menu
mb.menu.add_command(label='New Window')
mb.menu.add_command(label='Add Text')
mb.menu.add_command(label='Exit...')

main.mainloop()

Output

Tkinter menu
Tkinter menu

Explanation

  • Here we just have created tkinter window of 200 x 200 .
  • After we have create a Menubutton() with some options .
  • We can put options in menubutton() using add_command .

Example -Add actions to options

In above code , we have created a tkinter menu with some options . We can add functionality to these options . To do so use command  attribute of add_command() method . Example :

mb.menu.add_command(label=' Exit... ' , command = exit )

Here is the code to add actions to above options i.e New window , Add Text , exit :

from tkinter import *

main = Tk()
main.config(bg="white")
main.geometry("200x200")

def fun1():
    m = Tk()
    Lb = Label(m, text = "Hello Option 1 clicked \n",bg="yellow", fg='red', font = ('cursive',10))
    Lb.pack()
    m.mainloop()
def fun2():
    en = Entry(main)
    en.pack(pady=20)
    print(en.get())

    btn = Button(main, text="Add",command = lambda:Lb.config(text ="Welcome!!! "+ en.get()),bg='green',fg='white',width=100)
    btn.pack()

    Lb = Label(main, text = "Enter Your Name Above \n",fg='green', font = ('cursive',15))
    Lb.pack(pady=20)

mb = Menubutton(main , text = "Menu", relief = RAISED )
mb.pack()
mb.menu = Menu(mb)
mb["menu"] = mb.menu
mb.menu.add_command(label='New Window',command = fun1)
mb.menu.add_command(label='Add Text',command = fun2)
mb.menu.add_command(label='Exit...', command = exit)

main.mainloop()

Output – 1. click on new window

Tkinter menu
Tkinter menu

Output – 2. click on Add Text

Tkinter menu
Tkinter menu

Explanation

  • You can open new tkinter window on clicking Tkinter menu .
  • In above output , i have click Add Text  two times .
  • You can see there , command fun2() gets executed .
  • After function calling , there appears an entry box and Add button .
  • We can add text to tkinter window by filling text in Entry() and clicking on Add button .
  • You can exit the tkinter window on clicking Exit… option .

Other parameters to Tkinter menubutton

Sr No.

Parameter

Explanation

1
anchor
It is for the positioning of the text/image inside the label widget i.e. where it should be placed . Possible values are NNEESESSWWNW, or CENTER. Default value is CENTER
2
bg
Allows us to change the background of Tkinter menubutton widget.
3
bitmap
It allows us to add bitmat to a menubutton widget . If there is an image then tkinter will ignore the bitmap
4
bd
To set the width(size) of the border we can use bd . Border denotes the boundary of the widget .
5
compound
We combine the text and graphic on the same widget using compound. Possible values are  BOTTOM , TOP, LEFT, RIGHT and CENTER . Default value is NONE .
6
cursor
It allows us to set type of cursor for the menubutton widget . The defined cursor will show on mouse over to label widget . Possible values are dot , circle etc. and default value is arrow .
7
fg
Sets the color of the text on menubutton widget
8
height
It describes the height of the menubuttonl widget . It is depend on the text / image’s size by default /
10
font
It is the type of font to be use  .Tkinter menubutton allows us the text only in single font .
11
image
We can also set image on the menubutton using image  as an attribute . This image has the highest priority than text and bitmap .
12
justify
We can use justify attribute to set the alignment of multiple lines of the text . Possible values are LEFT, RIGHT and default value is CENTER .
13
padx
It allows us to add horizontal (left-right) space around the text and the border of the widget. Its default value is 1px .
14
pady
It allows us to add vertical ( top-bottom ) space around the text and the border of the widget. Its default value is 1px .
15
relief
Allows us to set the type of border . Possible values are SUNKENRAISEDGROOVE, and RIDGE and default value is FLAT .
15
state
It is the state or we can say visibility of the widget . Possible value is DESABLED and default value is NORMAL .
16
text
It is the plain text to be display in the menubutton widget . It has the lowest priority , can be ignore if there is an image or bitmap.
17
textvariable
It denotes the text to be display on the widget . It is used for dynamic text .
18
underline
We can underline the specific character with the text widget . Default value is -1 , which means no character underlined . We can underline character using its location i.e. 0 for the first character .
19
width
It is the width of the menubutton widget . If menubutton contains text then it is in number of text units  . Else if label contains image its value depend on the number of pixels . The default value is according to the content .
20
wraplength
We can set / limit the number of characters in each line using wraplength . Default value is 0, means text will place in newline only by ‘\n’ , otherwise in single line .
21

direction

It is the direction of tkinter menu according to the tkinter menubutton . Possible values are Tabove , below, LEFT and RIGHT . Default value is below (menu shown below the button )
22

disabledforeground

It is the color of the Menubutton() text when its state is disable . Default value is system specific .

So , it is all about the Tkinter menubutton , i hope you guys enjoyed the post . Thanks !!!

Tkinter Listbox operations

Tkinter Listbox operations

Tkinter Listbox operations : In our previous article , we have discuss about Listbox in Tkinter . Now we will discuss about operations in Tkinter Listbox . We can perform various operations to Tkinter Listbox , including insertion, deletion , selection etc .

If you have not read our previous article then you can visit the link below:

http://onlinetutorial.co.in/tkinter-listbox/

Insert element

In our previous article , we have discuss about  Tkinter Listbox insert() method . Let’s take a look again . Here is the syntax to do so :

Syntax

Listbox.insert(index , item)
  • index can be either an integer number or some special indexes including ACTIVE ( inserts after active item ) and END ( inserts at the end of the list ) .
  • item is the value( item ) to inserted in the list . It can either be a string or integer or other type .

Example

from tkinter import *

class list_operation:
    def __init__(self, master):
        Lb = Label(master , text="Python List Operations", font=("cursive",20), fg='red')
        Lb.grid(row = 0 , column=0)
        en = Entry(master)
        self.en = en
        en.grid(row = 1 , column=0)
        btn = Button(master, text = "Insert" , width=17, command = self.add)
        btn.grid(row = 2 , column=0, pady=2)
        Ls = Listbox(master)
        Ls.grid(row = 3 , column=0)
        self.Ls = Ls

    def add(self):
        x = self.en.get()
        self.Ls.insert(END,x)

main = Tk()

list_operation(main)
main.mainloop()

Output

Tkinter Listbox operations
Tkinter Listbox operations

Select  element

The main purpose of a listbox is to let user select one or more elements . To do so the curselection() method is used to get the selected items . Basically a list contain index values corresponding to the numbers .  It returns a list of index specifiers.Here is the syntax to do so :

Syntax

Listbox.curselection()

Example

from tkinter import *

class list_operation:
    def __init__(self, master):
        colors = ['red','green','blue','orange','white','black','purple']
        self.colors = colors
        Lb = Label(master , text="Python List Operations", font=("cursive",20), fg='red')
        Lb.grid(row = 0 , column=0)

        Ls = Listbox(master,selectmode=MULTIPLE)
        Ls.grid(row = 1 , column=0)
        self.Ls = Ls

        for color in colors:
            self.Ls.insert(END , color)
        btn = Button(text = "Select", command=self.select, bg="green" , width=17 , fg = 'white')
        btn.grid(row = 2 , column=0)
        def select(self):
            select = self.Ls.curselection()
        for i in select:
            print("Selected Item :",self.colors[i])
main = Tk()

list_operation(main)
main.mainloop()

Example

Tkinter Listbox operations
Tkinter Listbox operations

Delete element & get size

Tkinter allows us multiple operations(Tkinter Listbox operations) to do with lists . We also can delete selected elements from a list . You can delete single as well as multiple selected elements at one time . To do so delete() method is used .

To get the number of elements in a list you can call get() method .

Syntax

Listbox.delete(first , last)
  • first is the first element’s to be delete .
  • last is the last element’s index .
  • To delete / clear entire list elements you can use Listbox.delete(0 , END)

Example

Let’s take an example how to use delete() and get() in python tkinter .

from tkinter import *

class list_operation:
    def __init__(self, master):
        colors = ['red','green','blue','orange','white','black','purple']
        self.colors = colors
        Lb = Label(master , text="Python List Operations", font=("cursive",20), fg='red')
        Lb.grid(row = 0 , column=0)

        Ls = Listbox(master,selectmode=MULTIPLE)
        Ls.grid(row = 1 , column=0)
        self.Ls = Ls

        for color in colors:
            self.Ls.insert(END , color)
        btn = Button(text = "Delete", command=self.delt,  bg="red" , width=17 , fg = 'white')
        btn.grid(row = 2 , column=0)

    def delt(self):
        current = self.Ls.curselection()
        self.Ls.delete(current)
        print("Element {} deleted !!! Current size : {}".format(current,self.Ls.size()))

main = Tk()

list_operation(main)
main.mainloop()

Output

Tkinter Listbox operations
Tkinter Listbox operations

So , these are the basic Tkinter Listbox operations , i hope you guys enjoyed the post . Thanks !!!

Tkinter Listbox

Tkinter Listbox

Tkinter Listbox is an standard Tkinter widget  , it is rectangular area , from which user can select its elements . There may be multiple elements from which user can select . It also allows user to select more than one option(as in check-boxes) . By default the list contains string value . But we also can change variable to integers . All the list item have the same font-color and font-style . Number of selection is depend upon the widget configuration .

Syntax

Listbox( main_window , other_options )

– main_window

The main_window is the tkinter’s main window , there can only single main / parent window . All other widgets are placed in the main_window .

– other_options

There are various other options for layout , placement and style of the Tkinter Listbox including bg , height , selectbackground etc.

Example – Listbox in a given range with single selection

from tkinter import *
top = Tk()
def fun():
a = int(en1.get())
b = int(en2.get())
for i in range(a,b+1):
    Lb1.insert(END,i)
    print(Lb1.get(1))
l2 = Label(top,text="List in Given Range",font=('cursive',20),fg='red')
l2.grid(row=0,column=0,pady=2,columnspan=3)
l1 = Label(top,text="Enter Number 1")
l1.grid(row=1,column=0)
en1 = Entry(top)
en1.grid(row=1,column=1)

l1 = Label(text="Enter Number 2")
l1.grid(row=2,column=0)
en2 = Entry(top)
en2.grid(row=2,column=1)

btn = Button(top,text='click',width=20,fg='white',bg='green',command=fun)
btn.grid(row=3 ,column=0,columnspan=4,pady=4)

Lb1 = Listbox(top, width=20)
Lb1.grid(row=4 ,column = 0, columnspan=4)
top.mainloop()

Output

Tkinter listbox
Tkinter listbox

Explanation

  • As you can see in the image above , there are two Entry boxes and a button .
  • There is a command associate with submit button .
  • When we put a range / Year selection in the entry box .
  • Then there appears a list box of items in the given range .
  • It also prints the value 2001 , using Lb1.get(1) get method takes index as a parameter .

Example – Listbox with multiple selection

To create a list which allows user to select multiple items , then just give an attribute / option selectmode to the

Tkinter Listbox. There are four possible values for the selectmode , which are SINGLE , MULTIPLE , BROWSE  and EXTENDED . Default value is BROWSE .

You also can change the background of selected item and number of items by using selectbackground attribute . Its possible value can be name or hexadecimal value of any color .

For these changes you need to just change the following lines

Lb1 = Listbox(top, width=20, selectmode = MULTIPLE , selectbackground = 'green')

Output

Tkinter listbox
Tkinter listbox

Explanation

  • The code is same as above , it just select multiple elements .
  • The user can select multiple element on mouse click  to the number of elements (to select ).
  • We also can change select color , as there is green .
  • There are different another options for the Tkinter listbox and function associate with it .

If you want to learn more about Tkinter Listbox then you can visit the link below :

Tkinter Listbox Operations

So , it is all about the today’s article , i hope you guys enjoyed the post. Thanks !!!

Tkinter Label

Tkinter Label

Tkinter Label is a standard widget of tkinter . We can display any kind of text or image using this . It supports static and dynamic text as well . Basically Tkinter Label is just for the guidance . We can place a Tkinter Label in front of any Entry , Canvas widget to let user know the working of another widgets . It just displays the text or image i.e user can’t interact with it .

We also can place both the text and image on the same Label widget . Or we can display image to the background of any text .

In simple words we can say that Tkinter Label is used to display text or images on the Tkinter window.

What is static and Dynamic text ?

Static text is the text which remains same till the end of the program .

In other hands , dynamic text is the text which changes according to time . It does not remain the same .

Tkinter supports both static as well as dynamic text .

Syntax

Label(main_window , other_parameters )

main_window

It is the root or we can say parent window , which holds the other widgets . In Tkinter Label we have to pass this window  as a parameter to the Label() function . Passing the main_window as a parameter denotes that , Label() is a child of it .

other_parameters

There are number of other options that we can provide to a Label() widget . These can be for style , layout , size etc. of the Label widget . These options are described below .

Tkinter Label Parameters

Sr No.

Parameter

Explanation

1
anchor
It is for the positioning of the text/image inside the label widget i.e. where it should be placed . Possible values are NNEESESSWWNW, or CENTER. Default value is CENTER
2
bg
Allows us to change the background of Tkinter Label widget.
3
bitmap
It allows us to add bitmat to a Label widget . If there is an image then tkinter will ignore the bitmap
4
bd
To set the width(size) of the border we can use bd . Border denotes the boundary of the widget .
5
combine
We combine the text and image on the same widget using combine. Possible values are  BOTTOM , TOP, LEFT, RIGHT and CENTER . Default value is NONE .
6
cursor
It allows us to set type of cursor for the label widget . The defined cursor will show on mouse over to label widget . Possible values are dot , circle etc. and default value is arrow .
7
fg
Sets the color of the text on Label widget
8
height
It describes the height of the label widget . It is depend on the text / image’s size by default /
10
font
It is the type of font to be use in Label text .Tkinter Label allows us the text only in single font .
11
image
We can also set image on the Label using image  as an attribute . This image has the highest priority than text and bitmap .
12
justify
We can use justify attribute to set the alignment of multiple lines of the text . Possible values are LEFT, RIGHT and default value is CENTER .
13
padx
It allows us to add horizontal (left-right) space around the text and the border of the widget. Its default value is 1px .
14
pady
It allows us to add vertical ( top-bottom ) space around the text and the border of the widget. Its default value is 1px .
15
relief
Allows us to set the type of border . Possible values are SUNKENRAISEDGROOVE, and RIDGE and default value is FLAT .
15
state
It is the state or we can say visibility of the widget . Possible value is DESABLED and default value is NORMAL .
16
text
It is the plain text to be display in the Label widget . It has the lowest priority , can be ignore if there is an image or bitmap.
17
textvariable
It denotes the text to be display on the widget . It is used for dynamic text .
18
underline
We can underline the specific character with the text widget . Default value is -1 , which means no character underlined . We can underline character using its location i.e. 0 for the first character .
19
width
It is the width of the label widget . If label contains text then it is in number of text units  . Else if label contains image its value depend on the number of pixels . The default value is according to the content .
20
wraplength
We can set / limit the number of characters in each line using wraplength . Default value is 0, means text will place in newline only by ‘\n’ , otherwise in single line .

Example – Random text and random color in Tkinter Label

from tkinter import *
import random
main = Tk()
Textvar = StringVar()

def text():
    r = repr(random.randint(10,99))
    r2 = repr(random.randint(10,99))
    color = '#A'+r+'C'+r2
    label.config(bg=color, fg='white')
    label.config(text='Color Code \n' + color)

label = Label( main, height=8,width=20 ,relief=RIDGE, bd=2 )
label.pack()
button =Button(main, text=' Click To Change Text',command=text)
button.pack()
main.mainloop()

Output

Tkinter Label
Tkinter Label

Explanation

  • Here is a simple label and button .
  • The text of the label changes dynamically on button click .
  • As here the dynamic text is color code, generated by the randint() function .
  • Here is the static text as well which is “Color Code” .

So, it is all about the Label widget in Tkinter window . I hope you guys enjoyed the post . Thanks !!!

 

Tkinter Frame

Tkinter Frame

Tkinter Frame is an rectangular division on screen . We also can say that Tkinter frame is an geometry master for all other widgets . It is working as a container for other widgets . We can use it to set alignment and layout (padding) of the other widgets .

It is basically used for grouping the widgets in the parent window . We can use number of Tkinter frame widgets to set ting the alignment of the complex application .

Syntax

Frame(main_window , other_parameters)
  • main_window : It is the parent window of tkinter , in which we want to group another widgets. Most of the time is is the tkinter.Tk() window.
  • other_parameters : There are number of other parameters to add another options tp a Frame , including height , width , cursor type etc .

Other_parameters of Tkinter Frame

Sr No.
Parameter
Explanation
1
bg
We can use it to set background color of the Frame . By default it is same as the window color .
2
bd
The thickness of the border around the content of frame.
3
colormap
It allows you to specify which color map to use for the frame, and its child widgets .  It is not changeable  once the frame created .
4
cursor
It is the type of cursor , should appear when the mouse over to frame . Default value is arrow , possible values are dot , circle etc.
5
height
It allows us to set the height of the frame widget . Default value is 0 .
6
padx
It is the horizontal padding/ spacing between the frames . Default value is 0.
7
pady
It is the vertical padding between different widgets . Its default value is 0 .
8
relief
It is the type of border , you want to set around the content of frame . Default value is FLAT ,possible values are SUNKEN , RIDGE etc.
9
width
It is the width of the frame ,you want to set . It covers the content by default.

Example – Color Changing box on button click

Here i am going to create a simple tkinter application using Tkinter Frame widget . There are two boxes , which changes the color according to specified input in Entry box .

from tkinter import *

master = Tk()
f1 = Frame(master, bd=3, relief=RIDGE)
f1.pack()
input = Entry(f1)
input.pack(side=LEFT,padx=4)
input1 = Entry(f1)
input1.pack(side=LEFT,padx=4)

def change_color():
    f2.config(bg=input.get())
    f3.config(bg=input1.get())

f2 = Frame(master,bd=5, relief=RIDGE ,padx=10)
f2.pack(ipady=50,ipadx=50,pady=5,side=LEFT)

f3 = Frame(master,bd=5, relief=RIDGE ,padx=10)
f3.pack(ipady=50,ipadx=50,pady=5,side=RIGHT)

f4 = Frame(master,padx=10)
f4.pack(side=BOTTOM,pady=20)
e = Button(f4, text='Apply Color', command=change_color,pady=5,bd=3)
e.pack(anchor=S)
master.mainloop()

Output

Tkinter frame
Tkinter frame

Explanation

  1. Here are two input fields and two boxes (created using frames) .
  2. These boxes changes colors as per the user input color and click on button .
  3. It accepts both color name value and hexadecimal value (as shown in figure above ).
  4. When we click on Apply Color Button , it calls the change_color function which is responsible for changing color of boxes .
  5. Basically , this color is applied to the background of the Tkinter Frame using bg .  

If you want to learn more about tkinter widgets then you can visit the link below :

Tkinter Introduction and its widgets

So , it is all about the today’s article. I hope you guys enjoyed the post . Thanks!!!

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.