0% found this document useful (0 votes)
35 views51 pages

Tkinter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views51 pages

Tkinter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Python Tkinter

Tkinter
• Python provides the standard library Tkinter for creating the graphical
user interface for desktop based applications.
• Developing desktop-based applications with Python Tkinter is not a
complex task. The following steps can be used to create an empty
Tkinter top-level window.
1.import the Tkinter module.
2.Create the main application window.
3.Add the widgets like labels, buttons, frames, etc. to the window.
4.Call the main event loop so the actions can occur on the user's computer
screen.
Example

from tkinter import *


#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()
Tkinter widgets

SN Widget Description
1 Button The Button is used to add various kinds of buttons to the python application.

2 Canvas The canvas widget is used to draw the canvas on the window.
3 Checkbutton The Checkbutton is used to display the CheckButton on the window.
The entry widget is used to display the single-line text field to the user. It is
4 Entry
commonly used to accept user values.
It can be defined as a container to which, another widget can be added and
5 Frame
organized.
A label is a text used to display some message or information about the
6 Label
other widgets.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
9 Menu It is used to add menu items to the user.
10 Message The Message widget is used to display the message-box to the user.
SN Widget Description
The Radiobutton is different from a checkbutton. Here, the user is
11 Radiobutton provided with various options and the user can select only one
option among them.
12 Scale It is used to provide the slider to the user.
It provides the scrollbar to the user so that the user can scroll the
13 Scrollbar window up and down.
It is different from Entry because it provides a multi-line text field to
14 Text the user so that the user can write the text and edit the text inside
it.
14 Toplevel It is used to create a separate window container.
15 Spinbox It is an entry widget used to select from options of values.
It is like a container widget that contains horizontal or vertical
16 PanedWind panes.
ow
17 LabelFrame A LabelFrame is a container widget that acts as the container
This module is used to display the message-box in the desktop
18 MessageBox
based applications.
Python Tkinter Geometry

• The Tkinter geometry specifies the method by using which, the


widgets are represented on display. The python Tkinter provides the
following geometry methods.
1.The pack() method
2.The grid() method
3.The place() method
Python Tkinter pack() method
• The pack() widget is used to organize widget in the block. The positions
widgets added to the python application using the pack() method can be
controlled by using the various options specified in the method call.
However, the controls are less and widgets are generally added in the
less organized manner. The syntax to use the pack() is given below.

• widget.pack(options)
• A list of possible options that can be passed in pack() is given below.
• expand: If the expand is set to true, the widget expands to fill any space.
• Fill: By default, the fill is set to NONE. However, we can set it to X or Y to
determine whether the widget contains any extra space.
• size: it represents the side of the parent to which the widget is to be placed on
the window.
Example

from tkinter import *


parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
Python Tkinter grid() method

• The grid() geometry manager organizes the widgets in the tabular


form. We can specify the rows and columns as the options in the
method call. We can also specify the column span (width) or
rowspan(height) of a widget.
• This is a more organized way to place the widgets to the python
application. The syntax to use the grid() is given below.
• Syntax
• widget.grid(options)
• A list of possible options that can be passed inside the grid() method is given
below.
• Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
• Columnspan
The width of the widget. It represents the number of columns up to which, the column is
expanded.
• ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
• padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
• row
The row number in which the widget is to be placed. The topmost row is represented by 0.
• rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
• Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the widget
inside the cell. It may be the concatenation of the sticky letters representing the position
of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
Example
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()
Python Tkinter place() method
• The place() geometry manager organizes the widgets to the specific x
and y coordinates.

• Syntax
• widget.place(options)
• A list of possible options is given below.
• Anchor: It represents the exact position of the widget within the
container. The default value (direction) is NW (the upper left corner)
• bordermode: The default value of the border type is INSIDE that
refers to ignore the parent's inside the border. The other option is
OUTSIDE.
• height, width: It refers to the height and width in pixels.
• relheight, relwidth: It is represented as the float between 0.0 and 1.0
indicating the fraction of the parent's height and width.
• relx, rely: It is represented as the float between 0.0 and 1.0 that is the
offset in the horizontal and vertical direction.
• x, y: It refers to the horizontal and vertical offset in the pixels.
Example

from tkinter import *


top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
Python Tkinter Button

• The button widget is used to add various types of buttons to the


Python application. Python allows us to configure the look of the
button according to our requirements. Various options can be set or
reset depending on the requirements.
• We can also associate a method or function with a button which is
called when the button is pressed.
The syntax to use the button widget is given below.
• Syntax
W = Button(parent, options)
SN Option Description
It represents the background of the button when the mouse hover
1 activebackground
the button.
It represents the font color of the button when the mouse hover the
2 activeforeground
button.
3 Bd It represents the border width in pixels.
4 Bg It represents the background color of the button.
It is set to the function call which is scheduled when the function is
5 Command
called.
6 Fg Foreground color of the button.
7 Font The font of the button text.

The height of the button. The height is represented in the number of


8 Height
text lines for the textual lines or the number of pixels for the images.

10 Highlightcolor The color of the highlight when the button has the focus.
11 Image It is set to the image displayed on the button.
It illustrates the way by which the multiple text lines
are represented. It is set to LEFT for left justification,
12 justify
RIGHT for the right justification, and CENTER for the
center.
Additional padding to the button in the horizontal
13 Padx
direction.
Additional padding to the button in the vertical
14 pady
direction.
It represents the type of the border. It can be SUNKEN,
15 Relief
RAISED, GROOVE, and RIDGE.
This option is set to DISABLED to make the button
17 State unresponsive. The ACTIVE represents the active state
of the button.
18 Underline Set this option to make the button text underlined.
The width of the button. It exists as a number of
19 Width
letters for textual buttons or pixels for image buttons.
If the value is set to a positive number, the text lines
20 Wraplength
will be wrapped to fit within this length.
Example
#python application to create a simple button

from tkinter import *

top = Tk()

top.geometry("200x100")

b = Button(top,text = "Simple")

b.pack()

top.mainaloop()
from tkinter import *
top = Tk()
top.geometry("200x100")
def fun():
messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top,text = "Red",command = fun,activeforeground = "red",activebackground = "pink",pady=10)


b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=10)
b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady = 10)
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pady = 10)

b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)

top.mainloop()
Python Tkinter Canvas

• The canvas widget is used to add the structured graphics to the


python application. It is used to draw the graph and plots to the
python application. The syntax to use the canvas is given below.
• Syntax
w = canvas(parent, options)
SN Option Description
1 bd The represents the border width. The default width is 2.

2 bg It represents the background color of the canvas.

3 confine It is set to make the canvas unscrollable outside the scroll


region.
4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.

5 height It represents the size of the canvas in the vertical direction.

6 highlightcolor It represents the highlight color when the widget is focused.

7 relief It represents the type of the border. The possible values are
SUNKEN, RAISED, GROOVE, and RIDGE.

8 scrollregion It represents the coordinates specified as the tuple containing


the area of the canvas.
9 width It represents the width of the canvas.
If it is set to a positive value. The canvas is placed only
10 xscrollincrement to the multiple of this value.
If the canvas is scrollable, this attribute should be
11 xscrollcommand the .set() method of the horizontal scrollbar.
Works like xscrollincrement, but governs vertical
12 yscrollincrement movement.
If the canvas is scrollable, this attribute should be
13 yscrollcommand the .set() method of the vertical scrollbar.
Example

from tkinter import *


top = Tk()
top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200")
c.pack()

top.mainloop()
from tkinter import *

top = Tk()

top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200",width = 200)

arc = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")

c.pack()

top.mainloop()
Python Tkinter Checkbutton

• The Checkbutton is used to track the user's choices provided to the


application. In other words, we can say that Checkbutton is used to
implement the on/off selections.
• The Checkbutton can contain the text or images. The Checkbutton is
mostly used to provide many choices to the user among which, the
user needs to choose the one. It generally implements many of many
selections.
• The syntax to use the checkbutton is given below.
• Syntax
w = checkbutton(master, options)
SN Option Description
It represents the background color when the checkbutton is
1 activebackground
under the cursor.
It represents the foreground color of the checkbutton when
2 activeforeground
the checkbutton is under the cursor.
3 bg The background color of the button.

4 bitmap It displays an image (monochrome) on the button.

5 bd The size of the border around the corner.


It is associated with a function to be called when the state
6 command
of the checkbutton is changed.
The mouse pointer will be changed to the cursor name
7 cursor
when it is over the checkbutton.
It is the color which is used to represent the text of a
8 disableforeground
disabled checkbutton.
9 font It represents the font of the checkbutton.

10 fg The foreground color (text color) of the checkbutton.


11 height It represents the height of the checkbutton (number of lines). The default height is 1.

12 highlightcolor The color of the focus highlight when the checkbutton is under focus.

13 image The image used to represent the checkbutton.

14 justify This specifies the justification of the text if the text contains multiple lines.

The associated control variable is set to 0 by default if the button is unchecked. We can
15 offvalue
change the state of an unchecked variable to some other one.

The associated control variable is set to 1 by default if the button is checked. We can
16 onvalue
change the state of the checked variable to some other one.

17 padx The horizontal padding of the checkbutton


18 pady The vertical padding of the checkbutton.

19 relief The type of the border of the checkbutton. By default, it is set to FLAT.

20 selectcolor The color of the checkbutton when it is set. By default, it is red.


21 selectimage The image is shown on the checkbutton when it is set.
It represents the state of the checkbutton. By default, it
is set to normal. We can change it to DISABLED to make
22 state the checkbutton unresponsive. The state of the
checkbutton is ACTIVE when it is under focus.
It represents the index of the character in the text which
24 underline is to be underlined. The indexing starts with zero in the
text.
It represents the associated variable that tracks the state
25 variable of the checkbutton.
It represents the width of the checkbutton. It is
26 width represented in the number of characters that are
represented in the form of texts.
If this option is set to an integer number, the text will be
27 wraplength broken into the number of pieces.
Methods
The methods that can be called with the Checkbuttons
are described in the following table.

SN Method Description
1 deselect() It is called to turn off the checkbutton.
The checkbutton is flashed between the active and
2 flash() normal colors.
This will invoke the method associated with the
3 invoke() checkbutton.
4 select() It is called to turn on the checkbutton.
It is used to toggle between the different
5 toggle() Checkbuttons.
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue = 0, height = 2, width = 10)

chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1, offvalue = 0, height = 2, width = 10)

chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1, offvalue = 0, height = 2, width = 10)
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()

top.mainloop()
Python Tkinter Entry
• The Entry widget is used to provde the single line text-box to the user
to accept a value from the user. We can use the Entry widget to
accept the text strings from the user. It can only be used for one line
of text from the user. For multiple lines of text, we must use the text
widget.
The syntax to use the Entry widget is given below.
• Syntax
w = Entry (parent, options)
Entry*
Example
# !/usr/bin/python3

from tkinter import *

top = Tk()
top.geometry("400x250")

name = Label(top, text = "Name").place(x = 30,y = 50)


email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place(x = 30, y = 170)

e1 = Entry(top).place(x = 80, y = 50)


e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)

top.mainloop()
import tkinter as tk
from functools import partial
def call_result(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text="Result = %d" % result)
return
root = tk.Tk()
root.geometry('400x200+100+200')
root.title('Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()

labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)


labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)
call_result = partial(call_result, labelResult, number1, number2)
buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3, column=0)

root.mainloop()
Listbox

• The Listbox widget is used to display the list items to


the user. We can place only text items in the Listbox and
all text items contain the same font and color.
• The user can choose one or more items from the list
depending upon the configuration.
• The syntax to use the Listbox is given below.
w = Listbox(parent, options)
Example 1
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top,text = "A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
top.mainloop()
Example 2: Deleting the active
items from the list
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top,text = "A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
#this button will delete the selected item from the list
btn = Button(top, text = "delete", command = lambda listbox=listbox: listbox.delete(ANCHOR))
lbl.pack()
listbox.pack()
btn.pack()
top.mainloop()
Menubutton
• The Menubutton widget can be defined as the drop-down menu
that is shown to the user all the time. It is used to provide the
user a option to select the appropriate choice exist within the
application.
• The Menubutton is used to implement various types of menus in
the python application. A Menu is associated with the
Menubutton that can display the choices of the Menubutton
when clicked by the user.
• The syntax to use the python tkinter Menubutton is given below.
• Syntax
w = Menubutton(Top, options)
Example
from tkinter import *
top = Tk()
top.geometry("200x250")
menubutton = Menubutton(top, text = "Language", relief = FLAT)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_checkbutton(label = "Hindi", variable=IntVar())
menubutton.menu.add_checkbutton(label = "English", variable = IntVar())
menubutton.pack()
top.mainloop()
Python Tkinter Menu
• The Menu widget is used to create various types of
menus (top level, pull down, and pop up) in the python
application.
• The top-level menus are the one which is displayed just
under the title bar of the parent window. We need to
create a new instance of the Menu widget and add
various commands to it by using the add() method.
• The syntax to use the Menu widget is given below.
• Syntax
w = Menu(top, options)
Example
from tkinter import *
top = Tk()
def hello():
print("hello!")
# create a toplevel menu
menubar = Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=top.quit)
# display the menu
top.config(menu=menubar)
top.mainloop()
from tkinter import Toplevel, Button, Tk, Menu
top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
Radiobutton
• The Radiobutton widget is used to implement one-of-many
selection in the python application. It shows multiple choices to
the user out of which, the user can select only one out of them.
We can associate different methods with each of the radiobutton.
• We can display the multiple line text or images on the
radiobuttons. To keep track the user's selection the radiobutton, it
is associated with a single variable. Each button displays a single
value for that particular variable.
• The syntax to use the Radiobutton is given below.
• Syntax
w = Radiobutton(top, options)
from tkinter import *
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,
command=selection)
R1.pack( anchor = W )
R2 = Radiobutton(top, text="C++", variable=radio, value=2,
command=selection)
R2.pack( anchor = W )
R3 = Radiobutton(top, text="Java", variable=radio, value=3,
command=selection)
R3.pack( anchor = W)
label = Label(top)
label.pack()
Scale

• The Scale widget is used to implement the graphical slider


to the python application so that the user can slide through
the range of values shown on the slider and select the one
among them.
• We can control the minimum and maximum values along
with the resolution of the scale. It provides an alternative to
the Entry widget when the user is forced to select only one
value from the given range of values.
• The syntax to use the Scale widget is given below.
• Syntax
w = Scale(top, options)
Example
from tkinter import *
def select():
sel = "Value = " + str(v.get())
label.config(text = sel)
top = Tk()
top.geometry("200x100")
v = DoubleVar()
scale = Scale( top, variable = v, from_ = 1, to = 50, orient = HORIZONTAL)
scale.pack(anchor=CENTER)
btn = Button(top, text="Value", command=select)
btn.pack(anchor=CENTER)
label = Label(top)
label.pack()
top.mainloop()
Scrollbar

• The scrollbar widget is used to scroll down the content


of the other widgets like listbox, text, and canvas.
However, we can also create the horizontal scrollbars to
the Entry widget.
• The syntax to use the Scrollbar widget is given below.
• Syntax
w = Scrollbar(top, options)
Example

from tkinter import *


top = Tk()
sb = Scrollbar(top)
sb.pack(side = RIGHT, fill = Y)
mylist = Listbox(top, yscrollcommand = sb.set )
for line in range(30):
mylist.insert(END, "Number " + str(line))
mylist.pack( side = LEFT )
sb.config( command = mylist.yview )
mainloop()
Spinbox

• The Spinbox widget is an alternative to the Entry


widget. It provides the range of values to the user, out
of which, the user can select the one.
• It is used in the case where a user is given some fixed
number of values to choose from.
• We can use various options with the Spinbox to
decorate the widget. The syntax to use the Spinbox is
given below.
• Syntax
w = Spinbox(top, options)
Example
from tkinter import *
top = Tk()
top.geometry("200x200")
spin = Spinbox(top, from_= 0, to = 25)
spin.pack()
top.mainloop()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy