Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Unit 5.1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Unit 5.

Python - GUI Programming

We have previously seen how to write text-only programs which have


a command-line interface, or CLI. Now we will briefly look at creating a program with
a graphical user interface, or GUI.
We will see how to make a simple GUI which handles user input and output.
GUIs often use a form of OO programming which we call event-driven: the program
responds to events, which are actions that a user takes.

What is a GUI?
A Graphical User Interface(GUI) is the first thing your user sees and interacts
with when he opens your application or website. Having a good GUI goes a long way in
increasing your platform’s reputation and user count. A user interface usually includes
a host of visual elements like icons, buttons, graphics, displayed text, and several other
forms of input, like checkbox, text input boxes, and such.
It’s the combination of all these elements that makes up a vital part of your
application or website’s user experience. Input to these visual elements can be from
the usual mediums, such as keyboards, mice, and touchscreens.

Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. We would look this option in this chapter.
 wxPython − wxPython is essentially a Python extension module that acts as a
wrapper for the wxWidgets API. wxPython allows Python developers to create
native user interfaces that add zero additional overhead to the application. The
cross-platform capabilities of wxPython allow deployment to platforms like
Windows, Mac OS, Linux, and Unix-based systems with little to no
modifications.
 JPython − JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local machine.
 PyQt -The PyQt package is built around the Qt framework, which is a cross-
platform framework used for creating a plethora of applications for various
platforms. The PyQt5 package includes a detailed set of bindings for Python
based on the latest version v5 of the Qt application framework. PyQt5 is
also fully cross-platform. By leveraging the power of PyQt5, developers can
build applications for platforms like Windows, Mac, Linux, iOS, Android, and
more.
 Kivy-Written with a mix of Python and Cython, Kivy is an open-source GUI
framework for building some of the most intuitive user interfaces encompassing
multi-touch applications that implement Natural User Interface(NUI).
With Kivy, interface designers can code once and deploy to multiple platforms, while
the built-in support for OpenGL ES 2 allows them to use modern and powerful
graphics and design techniques. The most common use of the Kivy GUI
framework in the real-world can be seen in our Android and iOS applications. Other
widespread implementations of the framework can be seen in the user interfaces
of Linux, Windows, Raspberry Pi, and Mac OS devices.
 PySide2- PySide2 is built by the same company that gave us the widely popular
application development framework Qt. Upon looking closely, you’ll come across
the term “Qt for Python Project”, which is nothing but the task of porting PySide
to support Qt5, whereas the framework itself is now being called PySide2.

 PyGUI- The Python GUI Project, or the PyGUI framework as it is more


commonly known, is a simple API that enables developers to create user
interfaces using native elements for Python applications. Being a fairly
lightweight API, the PyGUI framework adds very little additional code between
the Python application and the target platform. PyGUI currently supports creating
applications for Unix-based systems, Windows machines, and Mac OS devices.

To make application development even easier for developers, the documentation


for the entire library is in Python, eliminating the need to refer to other GUI
libraries. PyGUI is available for Python 2 & 3 and yes, it does come with support
for extensions that let you use OpenGL and GTK.

 PyGTK - PyGTK is a set of wrappers written in Python and C for GTK + GUI
library. It is part of the GNOME project. It offers comprehensive tools for building
desktop applications in Python. This tutorial discusses the basic functionalities of
the different widgets found in the toolkit.
Comparison between Kivy and Tkinter

Kivy Tkinter

Kivy is an open-source and free python framework Tkinter is also another Python library for
for developing user interface apps along with developing GUI apps which is usually a
multi-touch apps. combination of the Tk GUI toolkit and Python
GUI framework.

To install Kivy, we need to use the pip command There is no need of installing Tkinter as it is
where pip needs to be installed in Python IDE. an in-built Python Standard library for GUI
development desktop apps.

In Kivy toolkit is usually developed, backed up, In Tkinter, there is a Tk toolkit that is
and then used in any commercial products. provided already with this Tkinter standard
Python library. We just need to import Tkinter
as tk.

These are used to develop mobile apps or multi- Tkinter is mainly used for developing
touch apps also along with desktop apps. desktop apps as it does not provide any
features for developing mobile apps, as in
Kivy.

Kivy can be run on Microsoft Windows, Raspberry Tkinter can be run on platforms such as
Pi, Android, iOS, and OS X or any other Microsoft Windows, Linux, Unix, and Mac OS
supported platforms for Kivy. X install versions of Python.

Kivy is an ope-source and 100% free version Tkinter is also an open-source, free software
under MITL that is Massachusetts Institute of version under PL that is Python License for
Technology License for developing commercial developing commercial products or apps.
apps or products.

Kivy is widely used for developing more dynamic Tkinter is mainly used by the developers that
and advanced apps in Python programming. are a beginner in developing GUI’s ad wants
to develop only GUI’s for computers.
Comparison of Kivy vs PyQt

Kivy PyQt

Kivy is also a cross-platform for developing mobile PyQt is a cross-platform which has a Python
applications and other multi-touch applications, binding for developing desktop apps with its
Hence Kivy can be defined as a Python built-in widgets and tools along with robust SQL
framework or Python library for developing user database support. Hence PyQt is defined as a
interface mobile and multi-touch applications that Python GUI framework for developing mostly
are open source and free. desktop software with the set of Python
versions v2 and v3 binding which is also free
and open source.

It can be used on Windows, Android, Raspberry It can be used on Windows, Android, Raspberry
Pi, iOS, and OS X or any other supported Pi, Linux, and Mac or any other supported
platforms for Kivy, and tools it can be integrated platforms for PyQt, and tools that can be
with Kivy are Python, Windows, Mac, and Linux. integrated with PyQt are Linux, Linux Mint, and
Windows.

Kivy is a 100% free version under MITL which PyQt is a free version under GPL which means
means Massachusetts Institute of Technology General Public License that is it is free only
License and can also be used in developing when the code written by you or the developer
commercial products. is not sold and if the code needs to be sold then
it no longer a free version in PyQt as it
considers it as commercial so we need to do
the payments or purchase it.

Kivy has a graphic engine that is built over In PyQt it has PyQtgraph which is built on
OpenGL with the most modern and fast pipelines. PyQt4 or PySide or NumPy which also having
fast pipelines as it has heavy leverage of
NumPy libraries.

It provides a toolkit that has 20 widgets such as It Provides various UI components such as
buttons, labels, Layouts, etc which is highly widgets which include buttons, menus, labels,
extensible which are written and test in Cython tables, etc, and all other designable widgets
using C and regression tests respectively. that are compatible with PyQt as QT provides
all these UI components in Python.

It can also use some input, devices, and protocols It also can be used with several input devices
such as Linux Kernel HID, Magic Mouse, Mtdev, such as keyboards or mouse and it does not
can also use some input, devices, and protocols offer much as in Kivy frameworks.
such as Linux Kernel HID, Magic Mouse, Mtdev,
etc with other input devices like mouse, dual
mouse Apple’s products, TUIO, etc.

The main drawback of Kivy is it is not that suitable The main drawback of PyQt is not available
for compiling or accessing complex application with any specific resources which mean it can
codes as it needs the combination of py and kV be used in the data in C++ only where it
languages along with the help of specific sometimes may make developers complex in
algorithms. designing as it needs more experience in C++.

This provides Kivy language which has better In PyQt, Qt is not any programming language
syntax and representation of all functionalities in as it is a tool but it mainly supports C++
the Kivy program with more precise and organized programming language to develop Qt.
in tree format.

Kivy is not recommendable for the applications PyQt is mostly recommended for building truly
which have native look for the desktops that are native applications that mostly rely on desktop
there would not be a proper match in appearance software or applications which means it most
or behavior-wise for Mac app on Mac suitable for desktop applications.

This mostly provides applications that work better This mostly provides applications that work
in mobile applications and other multi-touch or better with desktop applications or software
user interface application but comparatively less than any mobile applications or multi-touch
in desktop applications. applications.

There are many other interfaces available, which you can find them on the net.

Tkinter Programming

Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform
the following steps −
 Import the Tkinter module.
 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the
user.

Example

import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()

This would create a following window −

Tkinter Widgets

Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as
a brief description in the following table −
Sr.No. Operator & Description
1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes.
The user can select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting values
from a user.
5 Frame
The Frame widget is used as a container widget to organize other widgets.
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can
also contain images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.
8 Menubutton
The Menubutton widget is used to display menus in your application.
9 Menu
The Menu widget is used to provide various commands to a user. These
commands are contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting values
from a user.
11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons.
The user can select only one option at a time.
12 Scale
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as
list boxes.
14 Text
The Text widget is used to display text in multiple lines.
15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes,
arranged horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer
or container for complex window layouts.
19 tkMessageBox
This module is used to display message boxes in your applications.
Let us study these widgets in detail –

Standard attributes

Let us take a look at how some of their common attributes.such as sizes, colors and
fonts are specified.
 Dimensions
 Colors
 Fonts
 Anchors
 Relief styles
 Bitmaps
 Cursors
Let us study them briefly −

Geometry Management

All Tkinter widgets have access to specific geometry management methods, which
have the purpose of organizing widgets throughout the parent widget area. Tkinter
exposes the following geometry manager classes: pack, grid, and place.
 The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
 The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
 The place() Method − This geometry manager organizes widgets by placing
them in a specific position in the parent widget.

Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can
display text or images that convey the purpose of the buttons. You can attach a
function or a method to a button which is called automatically when you click the
button.

Syntax

Here is the simple syntax to create this widget −


w = Button ( master, option=value, ... )

Parameters
 master − This represents the parent window.
 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Sr.No. Option & Description
1
activebackground
Background color when the button is under the cursor.
2
activeforeground
Foreground color when the button is under the cursor.
3
bd
Border width in pixels. Default is 2.
4
bg
Normal background color.
5
command
Function or method to be called when the button is clicked.
6
fg
Normal foreground (text) color.
7
font
Text font to be used for the button's label.
8
height
Height of the button in text lines (for textual buttons) or pixels (for images).
9
highlightcolor
The color of the focus highlight when the widget has focus.
10
image
Image to be displayed on the button (instead of text).
11
justify
How to show multiple text lines: LEFT to left-justify each line; CENTER to center
them; or RIGHT to right-justify.
12
padx
Additional padding left and right of the text.
13
pady
Additional padding above and below the text.
14
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED,
GROOVE, and RIDGE.
15
state
Set this option to DISABLED to gray out the button and make it unresponsive. Has
the value ACTIVE when the mouse is over it. Default is NORMAL.
16
underline
Default is -1, meaning that no character of the text on the button will be
underlined. If nonnegative, the corresponding text character will be underlined.
17
width
Width of the button in letters (if displaying text) or pixels (if displaying an image).
18
wraplength
If this value is set to a positive number, the text lines will be wrapped to fit within
this length.

Methods

Following are commonly used methods for this widget −


Sr.No. Method & Description
1
flash()
Causes the button to flash several times between active and normal colors.
Leaves the button in the state it was in originally. Ignored if the button is disabled.
2
invoke()
Calls the button's callback, and returns what that function returns. Has no effect if
the button is disabled or there is no callback.

Example

import Tkinter
import tkMessageBox

top = Tkinter.Tk()

def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
top.mainloop()
When the above code is executed, it produces the following result –
Tkinter Canvas
The Canvas is a rectangular area intended for drawing pictures or other complex
layouts. You can place graphics, text, widgets or frames on a Canvas.

Syntax

Here is the simple syntax to create this widget −


w = Canvas ( master, option=value, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Sr.No. Option & Description


1
bd
Border width in pixels. Default is 2.
2
bg
Normal background color.
3
confine
If true (the default), the canvas cannot be scrolled outside of the scrollregion.
4
cursor
Cursor used in the canvas like arrow, circle, dot etc.
5
height
Size of the canvas in the Y dimension.
6
highlightcolor
Color shown in the focus highlight.
7
relief
Relief specifies the type of the border. Some of the values are SUNKEN, RAISED,
GROOVE, and RIDGE.
8
scrollregion
A tuple (w, n, e, s) that defines over how large an area the canvas can be scrolled,
where w is the left side, n the top, e the right side, and s the bottom.
9
width
Size of the canvas in the X dimension.
10
xscrollincrement
If you set this option to some positive dimension, the canvas can be positioned
only on multiples of that distance, and the value will be used for scrolling by
scrolling units, such as when the user clicks on the arrows at the ends of a
scrollbar.
11
xscrollcommand
If the canvas is scrollable, this attribute should be the .set() method of the
horizontal scrollbar.
12
yscrollincrement
Works like xscrollincrement, but governs vertical movement.
13
yscrollcommand
If the canvas is scrollable, this attribute should be the .set() method of the vertical
scrollbar.

The Canvas widget can support the following standard items −

arc − Creates an arc item, which can be a chord, a pieslice or a simple arc.
coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=0, extent=150, fill="blue")

image − Creates an image item, which can be an instance of either the BitmapImage
or the PhotoImage classes.
filename = PhotoImage(file = "sunshine.gif")
image = canvas.create_image(50, 50, anchor=NE, image=filename)

line − Creates a line item.


line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)
oval − Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for the oval.
oval = canvas.create_oval(x0, y0, x1, y1, options)

polygon − Creates a polygon item that must have at least three vertices.
oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)

Example

Try the following example yourself −


import Tkinter

top = Tkinter.Tk()

C = Tkinter.Canvas(top, bg="blue", height=250, width=300)

coord = 10, 50, 240, 210


arc = C.create_arc(coord, start=0, extent=150, fill="red")

C.pack()
top.mainloop()
When the above code is executed, it produces the following result −
Tkinter Checkbutton
The Checkbutton widget is used to display a number of options to a user as toggle
buttons. The user can then select one or more options by clicking the button
corresponding to each option.
You can also display images in place of text.

Syntax

Here is the simple syntax to create this widget −


w = Checkbutton ( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas.

Sr.No. Option & Description


1 activebackground
Background color when the checkbutton is under the cursor.
2 activeforeground
Foreground color when the checkbutton is under the cursor.
3 bg
The normal background color displayed behind the label and indicator.
4 bitmap
To display a monochrome image on a button.
5 bd
The size of the border around the indicator. Default is 2 pixels.
6 command
A procedure to be called every time the user changes the state of this
checkbutton.
7 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
8 disabledforeground
The foreground color used to render the text of a disabled checkbutton. The
default is a stippled version of the default foreground color.
9 font
The font used for the text.
10 fg
The color used to render the text.
11 height
The number of lines of text on the checkbutton. Default is 1.
12 highlightcolor
The color of the focus highlight when the checkbutton has the focus.
13 image
To display a graphic image on the button.
14 justify
If the text contains multiple lines, this option controls how the text is justified:
CENTER, LEFT, or RIGHT.
15 offvalue
Normally, a checkbutton's associated control variable will be set to 0 when it is
cleared (off). You can supply an alternate value for the off state by setting
offvalue to that value.
16 onvalue
Normally, a checkbutton's associated control variable will be set to 1 when it is
set (on). You can supply an alternate value for the on state by setting onvalue to
that value.
17 padx
How much space to leave to the left and right of the checkbutton and text.
Default is 1 pixel.
18 pady
How much space to leave above and below the checkbutton and text. Default is
1 pixel.
19 relief
With the default value, relief=FLAT, the checkbutton does not stand out from its
background. You may set this option to any of the other styles
20 selectcolor
The color of the checkbutton when it is set. Default is selectcolor="red".
21 selectimage
If you set this option to an image, that image will appear in the checkbutton
when it is set.
22 state
The default is state=NORMAL, but you can use state=DISABLED to gray out the
control and make it unresponsive. If the cursor is currently over the checkbutton,
the state is ACTIVE.
23 text
The label displayed next to the checkbutton. Use newlines ("\n") to display
multiple lines of text.
24 underline
With the default value of -1, none of the characters of the text label are
underlined. Set this option to the index of a character in the text (counting from
zero) to underline that character.
25 variable
The control variable that tracks the current state of the checkbutton. Normally
this variable is an IntVar, and 0 means cleared and 1 means set, but see the
offvalue and onvalue options above.
26 width
The default width of a checkbutton is determined by the size of the displayed
image or text. You can set this option to a number of characters and the
checkbutton will always have room for that many characters.
27 wraplength
Normally, lines are not wrapped. You can set this option to a number of
characters and all lines will be broken into pieces no longer than that number.

Methods
Following are commonly used methods for this widget −
Sr.No. Method & Description
1 deselect()
Clears (turns off) the checkbutton.
2 flash()
Flashes the checkbutton a few times between its active and normal colors, but
leaves it the way it started.
3 invoke()
You can call this method to get the same actions that would occur if the user
clicked on the checkbutton to change its state.
4 select()
Sets (turns on) the checkbutton.
5 toggle()
Clears the checkbutton if set, sets it if cleared.

Example
Try the following example yourself −
from Tkinter import *
import tkMessageBox
import Tkinter

top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
When the above code is executed, it produces the following result −

Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
 If you want to display multiple lines of text that can be edited, then you should
use the Text widget.
 If you want to display one or more lines of text that cannot be modified by the
user, then you should use the Label widget.
Syntax

Here is the simple syntax to create this widget −


w = Entry( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Sr.No. Option & Description


1 bg
The normal background color displayed behind the label and indicator.
2 bd
The size of the border around the indicator. Default is 2 pixels.
3 command
A procedure to be called every time the user changes the state of this checkbutton.
4 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
5 font
The font used for the text.
6 exportselection
By default, if you select text within an Entry widget, it is automatically exported to the
clipboard. To avoid this exportation, use exportselection=0.
7 fg
The color used to render the text.
8 highlightcolor
The color of the focus highlight when the checkbutton has the focus.
9 justify
If the text contains multiple lines, this option controls how the text is justified:
CENTER, LEFT, or RIGHT.
10 relief
With the default value, relief=FLAT, the checkbutton does not stand out from its
background. You may set this option to any of the other styles
11 selectbackground
The background color to use displaying selected text.
12 selectborderwidth
The width of the border to use around selected text. The default is one pixel.
13 selectforeground
The foreground (text) color of selected text.
14 show
Normally, the characters that the user types appear in the entry. To make a
.password. entry that echoes each character as an asterisk, set show="*".
15 state
The default is state=NORMAL, but you can use state=DISABLED to gray out the
control and make it unresponsive. If the cursor is currently over the checkbutton, the
state is ACTIVE.
16 textvariable
In order to be able to retrieve the current text from your entry widget, you must set
this option to an instance of the StringVar class.
17 width
The default width of a checkbutton is determined by the size of the displayed image
or text. You can set this option to a number of characters and the checkbutton will
always have room for that many characters.
18 xscrollcommand
If you expect that users will often enter more text than the onscreen size of the
widget, you can link your entry widget to a scrollbar.

Methods
Following are commonly used methods for this widget –

Sr.No. Method & Description


1 delete ( first, last=None )
Deletes characters from the widget, starting with the one at index first, up to but not
including the character at position last. If the second argument is omitted, only the
single character at position first is deleted.
2 get()
Returns the entry's current text as a string.
3 icursor ( index )
Set the insertion cursor just before the character at the given index.
4 index ( index )
Shift the contents of the entry so that the character at the given index is the leftmost
visible character. Has no effect if the text fits entirely within the entry.
5 insert ( index, s )
Inserts string s before the character at the given index.
6 select_adjust ( index )
This method is used to make sure that the selection includes the character at the
specified index.
7 select_clear()
Clears the selection. If there isn't currently a selection, has no effect.
8 select_from ( index )
Sets the ANCHOR index position to the character selected by index, and selects that
character.
9 select_present()
If there is a selection, returns true, else returns false.
10 select_range ( start, end )
Sets the selection under program control. Selects the text starting at the start index,
up to but not including the character at the end index. The start position must be
before the end position.
11 select_to ( index )
Selects all the text from the ANCHOR position up to but not including the character
at the given index.
12 xview ( index )
This method is useful in linking the Entry widget to a horizontal scrollbar.
13 xview_scroll ( number, what )
Used to scroll the entry horizontally. The what argument must be either UNITS, to
scroll by character widths, or PAGES, to scroll by chunks the size of the entry
widget. The number is positive to scroll left to right, negative to scroll right to left.

Example
from Tkinter import *

top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)

top.mainloop()
When the above code is executed, it produces the following result –

Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other
widgets in a somehow friendly way. It works like a container, which is responsible for
arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of
these widgets. A frame can also be used as a foundation class to implement complex
widgets.

Syntax

Here is the simple syntax to create this widget −


w = Frame ( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Sr.No. Option & Description


1 Bg
The normal background color displayed behind the label and indicator.
2 Bd
The size of the border around the indicator. Default is 2 pixels.
3 Cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
4 Height
The vertical dimension of the new frame.
5 highlightbackground
Color of the focus highlight when the frame does not have focus.
6 Highlightcolor
Color shown in the focus highlight when the frame has the focus.
7 highlightthickness
Thickness of the focus highlight.
8 Relief
With the default value, relief=FLAT, the checkbutton does not stand out from its
background. You may set this option to any of the other styles
9 Width
The default width of a checkbutton is determined by the size of the displayed
image or text. You can set this option to a number of characters and the
checkbutton will always have room for that many characters.

Example
Try the following example yourself −
from Tkinter import *

root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")


redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")


greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")


bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")


blackbutton.pack( side = BOTTOM)

root.mainloop()
When the above code is executed, it produces the following result −
Tkinter Label
This widget implements a display box where you can place text or images. The text
displayed by this widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and
span the text across multiple lines.

Syntax

Here is the simple syntax to create this widget −


w = Label ( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Sr.No. Option & Description


1 anchor
This options controls where the text is positioned if the widget has more space than
the text needs. The default is anchor=CENTER, which centers the text in the
available space.
2 bg
The normal background color displayed behind the label and indicator.
3 bitmap
Set this option equal to a bitmap or image object and the label will display that
graphic.
4 bd
The size of the border around the indicator. Default is 2 pixels.
5 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will
change to that pattern when it is over the checkbutton.
6 font
If you are displaying text in this label (with the text or textvariable option, the font
option specifies in what font that text will be displayed.
7 fg
If you are displaying text or a bitmap in this label, this option specifies the color of
the text. If you are displaying a bitmap, this is the color that will appear at the
position of the 1-bits in the bitmap.
8 height
The vertical dimension of the new frame.
9 image
To display a static image in the label widget, set this option to an image object.
10 justify
Specifies how multiple lines of text will be aligned with respect to each other: LEFT
for flush left, CENTER for centered (the default), or RIGHT for right-justified.
11 padx
Extra space added to the left and right of the text within the widget. Default is 1.
12 pady
Extra space added above and below the text within the widget. Default is 1.
13 relief
Specifies the appearance of a decorative border around the label. The default is
FLAT; for other values.
14 text
To display one or more lines of text in a label widget, set this option to a string
containing the text. Internal newlines ("\n") will force a line break.
15 textvariable
To slave the text displayed in a label widget to a control variable of class StringVar,
set this option to that variable.
16 underline
You can display an underline (_) below the nth letter of the text, counting from 0, by
setting this option to n. The default is underline=-1, which means no underlining.
17 width
Width of the label in characters (not pixels!). If this option is not set, the label will be
sized to fit its contents.
18 wraplength
You can limit the number of characters in each line by setting this option to the
desired number. The default value, 0, means that lines will be broken only at
newlines.

Example
Try the following example yourself −
from Tkinter import *

root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )

var.set("Hey!? How are you doing?")


label.pack()
root.mainloop()
When the above code is executed, it produces the following result –

Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
In order to implement this functionality, each group of radiobuttons must be associated
to the same variable and each one of the buttons must symbolize a single value. You
can use the Tab key to switch from one radionbutton to another.

Syntax

Here is the simple syntax to create this widget −


w = Radiobutton ( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas.
Sr.No. Option & Description
1 activebackground
The background color when the mouse is over the radiobutton.
2 activeforeground
The foreground color when the mouse is over the radiobutton.
3 anchor
If the widget inhabits a space larger than it needs, this option specifies where the
radiobutton will sit in that space. The default is anchor=CENTER.
4 bg
The normal background color behind the indicator and label.
5 bitmap
To display a monochrome image on a radiobutton, set this option to a bitmap.
6 borderwidth
The size of the border around the indicator part itself. Default is 2 pixels.
7 command
A procedure to be called every time the user changes the state of this radiobutton.
8 cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change
to that pattern when it is over the radiobutton.
9 font
The font used for the text.
10 fg
The color used to render the text.
11 height
The number of lines (not pixels) of text on the radiobutton. Default is 1.
12 highlightbackground
The color of the focus highlight when the radiobutton does not have focus.
13 highlightcolor
The color of the focus highlight when the radiobutton has the focus.
14 image
To display a graphic image instead of text for this radiobutton, set this option to an
image object.
15 justify
If the text contains multiple lines, this option controls how the text is justified:
CENTER (the default), LEFT, or RIGHT.
16 padx
How much space to leave to the left and right of the radiobutton and text. Default is 1.
17 pady
How much space to leave above and below the radiobutton and text. Default is 1.
18 relief
Specifies the appearance of a decorative border around the label. The default is
FLAT; for other values.
19 selectcolor
The color of the radiobutton when it is set. Default is red.
20 selectimage
If you are using the image option to display a graphic instead of text when the
radiobutton is cleared, you can set the selectimage option to a different image that
will be displayed when the radiobutton is set.
21 state
The default is state=NORMAL, but you can set state=DISABLED to gray out the
control and make it unresponsive. If the cursor is currently over the radiobutton, the
state is ACTIVE.
22 text
The label displayed next to the radiobutton. Use newlines ("\n") to display multiple
lines of text.
23 textvariable
To slave the text displayed in a label widget to a control variable of class StringVar,
set this option to that variable.
24 underline
You can display an underline (_) below the nth letter of the text, counting from 0, by
setting this option to n. The default is underline=-1, which means no underlining.
25 value
When a radiobutton is turned on by the user, its control variable is set to its current
value option. If the control variable is an IntVar, give each radiobutton in the group a
different integer value option. If the control variable is a StringVar, give each
radiobutton a different string value option.
26 variable
The control variable that this radiobutton shares with the other radiobuttons in the
group. This can be either an IntVar or a StringVar.
27 width
Width of the label in characters (not pixels!). If this option is not set, the label will be
sized to fit its contents.
28 wraplength
You can limit the number of characters in each line by setting this option to the
desired number. The default value, 0, means that lines will be broken only at
newlines.
Methods
Sr.No. Method & Description
1 deselect()
Clears (turns off) the radiobutton.
2 flash()
Flashes the radiobutton a few times between its active and normal colors, but leaves
it the way it started.
3 invoke()
You can call this method to get the same actions that would occur if the user clicked
on the radiobutton to change its state.
4 select()
Sets (turns on) the radiobutton.

Example
Try the following example yourself −
from Tkinter import *

def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)

root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )

R2 = Radiobutton(root, text="Option 2", variable=var, value=2,


command=sel)
R2.pack( anchor = W )

R3 = Radiobutton(root, text="Option 3", variable=var, value=3,


command=sel)
R3.pack( anchor = W)

label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result –
Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and
format the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections of
the text, and apply changes to those areas. Moreover, you can embed windows and
images in the text because this widget was designed to handle both plain and
formatted text.

Syntax

Here is the simple syntax to create this widget −


w = Text ( master, option, ... )

Parameters

 master − This represents the parent window.


 options − Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.

Sr.No. Option & Description


1 bg
The default background color of the text widget.
2 bd
The width of the border around the text widget. Default is 2 pixels.
3 cursor
The cursor that will appear when the mouse is over the text widget.
4 exportselection
Normally, text selected within a text widget is exported to be the selection in the
window manager. Set exportselection=0 if you don't want that behavior.
5 font
The default font for text inserted into the widget.
6 fg
The color used for text (and bitmaps) within the widget. You can change the color for
tagged regions; this option is just the default.
7 height
The height of the widget in lines (not pixels!), measured according to the current font
size.
8 highlightbackground
The color of the focus highlight when the text widget does not have focus.
9 highlightcolor
The color of the focus highlight when the text widget has the focus.
10 highlightthickness
The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress
display of the focus highlight.
11 insertbackground
The color of the insertion cursor. Default is black.
12 insertborderwidth
Size of the 3-D border around the insertion cursor. Default is 0.
13 insertofftime
The number of milliseconds the insertion cursor is off during its blink cycle. Set this
option to zero to suppress blinking. Default is 300.
14 insertontime
The number of milliseconds the insertion cursor is on during its blink cycle. Default is
600.
15 insertwidth
Width of the insertion cursor (its height is determined by the tallest item in its line).
Default is 2 pixels.
16 padx
The size of the internal padding added to the left and right of the text area. Default is
one pixel.
17 pady
The size of the internal padding added above and below the text area. Default is one
pixel.
18 relief
The 3-D appearance of the text widget. Default is relief=SUNKEN.
19 selectbackground
The background color to use displaying selected text.
20 selectborderwidth
The width of the border to use around selected text.
21 spacing1
This option specifies how much extra vertical space is put above each line of text. If a
line wraps, this space is added only before the first line it occupies on the display.
Default is 0.
22 spacing2
This option specifies how much extra vertical space to add between displayed lines of
text when a logical line wraps. Default is 0.
23 spacing3
This option specifies how much extra vertical space is added below each line of text. If
a line wraps, this space is added only after the last line it occupies on the display.
Default is 0.
24 state
Normally, text widgets respond to keyboard and mouse events; set state=NORMAL to
get this behavior. If you set state=DISABLED, the text widget will not respond, and you
won't be able to modify its contents programmatically either.
25 tabs
This option controls how tab characters position text.
26 width
The width of the widget in characters (not pixels!), measured according to the current
font size.
27 wrap
This option controls the display of lines that are too wide. Set wrap=WORD and it will
break the line after the last word that will fit. With the default behavior, wrap=CHAR,
any line that gets too long will be broken at any character.
28 xscrollcommand
To make the text widget horizontally scrollable, set this option to the set() method of
the horizontal scrollbar.
29 yscrollcommand
To make the text widget vertically scrollable, set this option to the set() method of the
vertical scrollbar.

Methods
Text objects have these methods −
Sr.No. Methods & Description
1 delete(startindex [,endindex])
This method deletes a specific character or a range of text.
2 get(startindex [,endindex])
This method returns a specific character or a range of text.
3 index(index)
Returns the absolute value of an index based on the given index.
4 insert(index [,string]...)
This method inserts strings at the specified index location.
5 see(index)
This method returns true if the text located at the index position is visible.

Text widgets support three distinct helper structures: Marks, Tabs, and Indexes −
Marks are used to bookmark positions between two characters within a given text. We
have the following methods available when handling marks –

Sr.No. Methods & Description


1 index(mark)
Returns the line and column location of a specific mark.
2 mark_gravity(mark [,gravity])
Returns the gravity of the given mark. If the second argument is provided, the gravity is
set for the given mark.
3 mark_names()
Returns all marks from the Text widget.
4 mark_set(mark, index)
Informs a new position to the given mark.
5 mark_unset(mark)
Removes the given mark from the Text widget.
Tags are used to associate names to regions of text which makes easy the task of
modifying the display settings of specific text areas. Tags are also used to bind event
callbacks to specific ranges of text.
Following are the available methods for handling tabs −
Sr.No. Methods & Description
1 tag_add(tagname, startindex[,endindex] ...)
This method tags either the position defined by startindex, or a range delimited by the
positions startindex and endindex.
2 tag_config
You can use this method to configure the tag properties, which include, justify(center,
left, or right), tabs(this property has the same functionality of the Text widget tabs's
property), and underline(used to underline the tagged text).
3 tag_delete(tagname)
This method is used to delete and remove a given tag.
4 tag_remove(tagname [,startindex[.endindex]] ...)
After applying this method, the given tag is removed from the provided area without
deleting the actual tag definition.

Example
Try the following example yourself −
from Tkinter import *

def onclick():
pass

root = Tk()
text = Text(root)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()

text.tag_add("here", "1.0", "1.4")


text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()

When the above code is executed, it produces the following result −

You might also like