BSc (ECS) Python - II Semester 6th

Python-II

Unit – I

Multithreading :

This article covers the basics of multithreading in Python programming language. Just like multiprocessing, multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used.

Let us first understand the concept of thread in computer architecture.

Thread

In computing, a process is an instance of a computer program that is being executed. Any process has 3 basic components:

  • An executable program.
  • The associated data needed by the program (variables, work space, buffers, etc.)
  • The execution context of the program (State of process)

thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System).

In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process!

A thread contains all this information in a Thread Control Block (TCB):

  • Thread Identifier: Unique id (TID) is assigned to every new thread
  • Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s scope.
  • Program counter: a register which stores the address of the instruction currently being executed by thread.
  • Thread state: can be running, ready, waiting, start or done.
  • Thread’s register set: registers assigned to thread for computations.
  • Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.

Consider the diagram below to understand the relation between process and its thread:

Multithreading

Multiple threads can exist within one process where:

  • Each thread contains its own register set and local variables (stored in stack).
  • All thread of a process share global variables (stored in heap) and the program code.

Consider the diagram below to understand how multiple threads exist in memory:

Multithreading is defined as the ability of a processor to execute multiple threads concurrently.

In a simple, single-core CPU, it is achieved using frequent switching between threads. This is termed as context switching. In context switching, the state of a thread is saved and state of another thread is loaded whenever any interrupt (due to I/O or manually set) takes place. Context switching takes place so frequently that all the threads appear to be running parallely (this is termed as multitasking).

Consider the diagram below in which a process contains two active threads:

Understanding threads

As many others languages, Python provides a great and simple library to use threads. This library includes all required objects and functions that you will need to do parallel programming and manage concurrent data access between threads. This article explains how to use python threads with a simple and common example based on a bank account. It will provide you the basic understanding of python thread in order to introduce you to the Python Global Interpreter Lock issue covered in another article.

Difference between Process and a Thread

Process
Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

Thread
A thread is an entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread’s set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread’s process. Threads can also have their own security context, which can be used for impersonating clients.

Creating Threads

Python Thread Creation Using Class

Let us understand by using code.

import threading
class mythread(threading.Thread):
  def __init__(self, i):
  threading.Thread.__init__(self)
self.h = i
def run(self):
  print“ Value send“, self.h
thread1 = mythread(1)
thread1.start()
  • New class mythread inherits the Python threading.Thread class.
  • __init__(self [,args]): Override the constructor.
  • run(): This is the section where you can put your logic part.
  • start(): The start() method starts a Python thread.
  • The mythread class overrides the constructor, so the base class constructor (Thread.__init__()) must be invoked.

Python Thread Creation Using a Function

import threading
def fun1(a, b):
  c = a + b
print(c)
thread1 = threading.Thread(target = fun1, args = (12, 10))
thread1.start()

The above code is very simple. Just create a function and get it run by a thread. The syntax

threading.Thread(target=fun1, args=(12,10)) creates a thread, the target = fun1

specifies the function to be run and args indicates the tuple which contains the argument to be passed to the function.

Thread Synchronization

Synchronizing Access to Shared Resources #

One important issue when using threads is to avoid conflicts when more than one thread needs to access a single variable or other resource. If you’re not careful, overlapping accesses or modifications from multiple threads may cause all kinds of problems, and what’s worse, those problems have a tendency of appearing only under heavy load, or on your production servers, or on some faster hardware that’s only used by one of your customers.

For example, consider a program that does some kind of processing, and keeps track of how many items it has processed:

counter = 0

def process_item(item):
    global counter
    ... do something with item ...
    counter += 1

If you call this function from more than one thread, you’ll find that the counter isn’t necessarily accurate. It works in most cases, but sometimes misses one or more items. The reason for this is that the increment operation is actually executed in three steps; first, the interpreter fetches the current value of the counter, then it calculates the new value, and finally, it writes the new value back to the variable.

If another thread gets control after the current thread has fetched the variable, it may fetch the variable, increment it, and write it back, before the current thread does the same thing. And since they’re both seeing the same original value, only one item will be accounted for.

Another common problem is access to incomplete or inconsistent state, which can happen if one thread is initializing or updating some non-trivial data structure, and another thread attempts to read the structure while it’s being updated.

Atomic Operations #

The simplest way to synchronize access to shared variables or other resources is to rely on atomic operations in the interpreter. An atomic operation is an operation that is carried out in a single execution step, without any chance that another thread gets control.

In general, this approach only works if the shared resource consists of a single instance of a core data type, such as a string variable, a number, or a list or dictionary. Here are some thread-safe operations:

  • reading or replacing a single instance attribute
  • reading or replacing a single global variable
  • fetching an item from a list
  • modifying a list in place (e.g. adding an item using append)
  • fetching an item from a dictionary
  • modifying a dictionary in place (e.g. adding an item, or calling the clearmethod)

Note that as mentioned earlier, operations that read a variable or attribute, modifies it, and then writes it back are not thread-safe. Another thread may update the variable after it’s been read by the current thread, but before it’s been updated.

Also note that Python code may be executed when objects are destroyed, so even seemingly simple operations may cause other threads to run, and may thus cause conflicts. When in doubt, use explicit locks.

Locks #

Locks are the most fundamental synchronization mechanism provided by the threading module. At any time, a lock can be held by a single thread, or by no thread at all. If a thread attempts to hold a lock that’s already held by some other thread, execution of the first thread is halted until the lock is released.

Locks are typically used to synchronize access to a shared resource. For each shared resource, create a Lock object. When you need to access the resource, call acquire to hold the lock (this will wait for the lock to be released, if necessary), and call release to release it:

lock = Lock()

lock.acquire() # will block if lock is already held
... access shared resource
lock.release()

For proper operation, it’s important to release the lock even if something goes wrong when accessing the resource. You can use try-finally for this purpose:

lock.acquire()
try:
    ... access shared resource
finally:
    lock.release() # release lock, no matter what

In Python 2.5 and later, you can also use the with statement. When used with a lock, this statement automatically acquires the lock before entering the block, and releases it when leaving the block:

from __future__ import with_statement # 2.5 only

with lock:
    ... access shared resource

The acquire method takes an optional wait flag, which can be used to avoid blocking if the lock is held by someone else. If you pass in False, the method never blocks, but returns False if the lock was already held:

if not lock.acquire(False):
    ... failed to lock the resource
else:
    try:
        ... access shared resource
    finally:
        lock.release()

You can use the locked method to check if the lock is held. Note that you cannot use this method to determine if a call to acquire would block or not; some other thread may have acquired the lock between the method call and the next statement.

if not lock.locked():
    # some other thread may run before we get
    # to the next line
    lock.acquire() # may block anyway

Problems with Simple Locking #

The standard lock object doesn’t care which thread is currently holding the lock; if the lock is held, any thread that attempts to acquire the lock will block, even if the same thread is already holding the lock. Consider the following example:

lock = threading.Lock()

def get_first_part():
    lock.acquire()
    try:
        ... fetch data for first part from shared object
    finally:
        lock.release()
    return data

def get_second_part():
    lock.acquire()
    try:
        ... fetch data for second part from shared object
    finally:
        lock.release()
    return data

Here, we have a shared resource, and two access functions that fetch different parts from the resource. The access functions both use locking to make sure that no other thread can modify the resource while we’re accessing it.

Now, if we want to add a third function that fetches both parts, we quickly get into trouble. The naive approach is to simply call the two functions, and return the combined result:

def get_both_parts():
    first = get_first_part()
    second = get_second_part()
    return first, second

The problem here is that if some other thread modifies the resource between the two calls, we may end up with inconsistent data. The obvious solution to this is to grab the lock in this function as well:

def get_both_parts():
    lock.acquire()
    try:
        first = get_first_part()
        second = get_second_part()
    finally:
        lock.release()
    return first, second

However, this won’t work; the individual access functions will get stuck, because the outer function already holds the lock. To work around this, you can add flags to the access functions that enables the outer function to disable locking, but this is error-prone, and can quickly get out of hand. Fortunately, the threadingmodule contains a more practical lock implementation; re-entrant locks.

Re-Entrant Locks (RLock) #

The RLock class is a version of simple locking that only blocks if the lock is held by another thread. While simple locks will block if the same thread attempts to acquire the same lock twice, a re-entrant lock only blocks if another thread currently holds the lock. If the current thread is trying to acquire a lock that it’s already holding, execution continues as usual.

lock = threading.Lock()
lock.acquire()
lock.acquire() # this will block

lock = threading.RLock()
lock.acquire()
lock.acquire() # this won't block

The main use for this is nested access to shared resources, as illustrated by the example in the previous section. To fix the access methods in that example, just replace the simple lock with a re-entrant lock, and the nested calls will work just fine.

lock = threading.RLock()

def get_first_part():
    ... see above

def get_second_part():
    ... see above

def get_both_parts():
    ... see above

With this in place, you can fetch either the individual parts, or both parts at once, without getting stuck or getting inconsistent data.

Note that this lock keeps track of the recursion level, so you still need to call release once for each call to acquire.

Semaphores #

A semaphore is a more advanced lock mechanism. A semaphore has an internal counter rather than a lock flag, and it only blocks if more than a given number of threads have attempted to hold the semaphore. Depending on how the semaphore is initialized, this allows multiple threads to access the same code section simultaneously.

semaphore = threading.BoundedSemaphore()
semaphore.acquire() # decrements the counter
... access the shared resource
semaphore.release() # increments the counter

The counter is decremented when the semaphore is acquired, and incremented when the semaphore is released. If the counter reaches zero when acquired, the acquiring thread will block. When the semaphore is incremented again, one of the blocking threads (if any) will run.

Semaphores are typically used to limit access to resource with limited capacity, such as a network connection or a database server. Just initialize the counter to the maximum number, and the semaphore implementation will take care of the rest.

max_connections = 10

semaphore = threading.BoundedSemaphore(max_connections)

If you don’t pass in a value, the counter is initialized to 1.

Python’s threading module provides two semaphore implementations; the Semaphore class provides an unlimited semaphore which allows you to call release any number of times to increment the counter. To avoid simple programming errors, it’s usually better to use the BoundedSemaphore class, which considers it to be an error to call release more often than you’ve called acquire.

Deadlock of Threads

All a deadlock means is that one or more threads are blocked from making any progress, so you can simulate it with a single thread. Just put a while True: around the sleep(10).

In realistic cases, you usually have two threads blocking each other from progress at the same time. For example, maybe they’ve taken a pair of locks in reverse order, so thread 1 won’t release lock 1 until it gets lock 2, but thread 2 won’t release lock 2 until it gets lock 1. So, it might be better to simulate it by having two threads block permanently.

If you want to actually create a deadlock, the simplest way is to have the threads literally block on each other: add thread2.join() to f1, and thread1.join() to f2. Then f1 can’t finish until f2 does, f2 can’t finish until f1 does, so neither one can ever finish.

However, if you want to create a realistic deadlock, you will almost certainly want to use synchronization objects like threading.Lock to do something like the two-lock scenario described above.

Also, how can I have each thread run after the other?

Well, the easy way would be to not use threads in the first place. But if you really want, just do this:

thread1.start()
thread1.join()
thread2.start()
thread2.join()
thread3.start()
thread3.join()

Also can I list all the threads that are currently running in my script?

See threading.enumerate(). You usually don’t want to use this except for debugging purposes; keep track of the threads as you create them, if you want to have access to them later (as you’re doing).

or give them priorities ?

As the docs say:

currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted.

If you want this, you have to step outside of threading and, e.g., use native APIs via ctypeswin32api, etc.

Avoiding Deadlock in a Program

Learn parallel programming techniques using Python and explore the many ways you can write code that allows more than one task to occur at a time. First, discover how to develop and implement efficient software architecture that is set up to take advantage of thread-based and process-based parallelism. Next, find out how to use Python modules for asynchronous programming. Then, explore GPU programming using PyCUDA, NumbaPro, and PyOpenCL. This course provides extensive coverage of synchronizing processes, streamlining communication, reducing operations, and optimizing code so you can select and implement the right parallel processing solutions for your applications.

Unit – II

GUI Programming

GUI in Python

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
To create a tkinter:

  1. Importing the module – tkinter
  2. Create the main window (container)
  3. Add any number of widgets to the main window
  4. Apply the event Trigger on the widgets.

Importing tkinter is same as importing any other module in the python code. Note that the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x is ‘tkinter’.

import tkinter

There are two main methods used you the user need to remember while creating the Python application with GUI.

  1. Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1): To create a main window, tkinter offers a method ‘Tk(screenName=None,  baseName=None,  className=’Tk’,  useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:m=tkinter.Tk() where m is the name of the main window object
  2. mainloop(): There is a method known by the name mainloop() is used when you are ready for the application to run. mainloop() is an infinite loop used to run the application, wait for an event to occur and process the event till the window is not closed.m.mainloop()filter_nonebrightness_4import tkinter m = tkinter.Tk() ''' widgets are added here '''m.mainloop()

tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in the parent windows. There are mainly three geometry manager classes class.

  1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
  2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent widget.
  3. place() method:It organizes the widgets by placing them on specific positions directed by the programmer.

There are a number of widgets which you can put in your tkinter application. Some of the major widgets are explained below:

  1. Button:To add a button in your application, this widget is used.
    The general syntax is:w=Button(master, option=value)master is the parameter used to represent the parent window.
    There are number of options which are used to change the format of the Buttons. Number of options can be passed as parameters separated by commas. Some of them are listed below.

    • activebackground: to set the background color when button is under the cursor.
    • activeforeground: to set the foreground color when button is under the cursor.
    • bg: to set he normal background color.
    • command: to call a function.
    • font: to set the font on the button label.
    • image: to set the image on the button.
    • width: to set the width of the button.
    • height: to set the height of the button.
    filter_noneeditplay_arrowbrightness_4import tkinter as tk r = tk.Tk() r.title('Counting Seconds') button = tk.Button(r, text='Stop', width=25, command=r.destroy) button.pack() r.mainloop() Output:
  2. Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
    The general syntax is:w = Canvas(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bd: to set the border width in pixels.
    • bg: to set the normal background color.
    • cursor: to set the cursor used in the canvas.
    • highlightcolor: to set the color shown in the focus highlight.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *master = Tk() w = Canvas(master, width=40, height=60) w.pack() canvas_height=20canvas_width=200y = int(canvas_height / 2) w.create_line(0, y, canvas_width, y ) mainloop() Output:
  3. CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons. The general syntax is:w = CheckButton(master, option=value)There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • Title: To set the title of the widget.
    • activebackground: to set the background color when widget is under the cursor.
    • activeforeground: to set the foreground color when widget is under the cursor.
    • bg: to set he normal backgrouSteganographyBreakSecret Code:Attach a File:nd color.
    • command: to call a function.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *master = Tk() var1 = IntVar() Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W) var2 = IntVar() Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W) mainloop() Output:
  4. Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.
    The general syntax is:w=Entry(master, option=value) master is the parameter used to represent the parent window.
    There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bd: to set the border width in pixels.
    • bg: to set the normal background color.
    • cursor: to set the cursor used.
    • command: to call a function.
    • highlightcolor: to set the color shown in the focus highlight.
    • width: to set the width of the button.
    • height: to set the height of the button.
    filter_noneeditplay_arrowbrightness_4from tkinter import *master = Tk() Label(master, text='First Name').grid(row=0) Label(master, text='Last Name').grid(row=1) e1 = Entry(master) e2 = Entry(master) e1.grid(row=0, column=1) e2.grid(row=1, column=1) mainloop() Output:
  5. Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The general syntax is:w = Frame(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.

    • highlightcolor: To set the color of the focus highlight when widget has to be focused.
    • bd: to set the border width in pixels.
    • bg: to set the normal background color.
    • cursor: to set the cursor used.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from 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() Output:
  6. Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.
    The general syntax is:w=Label(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bg: to set he normal background color.
    • bg to set he normal background color.
    • command: to call a function.
    • font: to set the font on the button label.
    • image: to set the image on the button.
    • width: to set the width of the button.
    • height” to set the height of the button.
    filter_noneeditplay_arrowbrightness_4from tkinter import *root = Tk() w = Label(root, text='GeeksForGeeks.org!') w.pack() root.mainloop() Output:
  7. Listbox: It offers a list to the user from which the user can accept any number of options.
    The general syntax is:w = Listbox(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • highlightcolor: To set the color of the focus highlight when widget has to be focused.
    • bg: to set he normal background color.
    • bd: to set the border width in pixels.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import * top = Tk() Lb = Listbox(top) Lb.insert(1, 'Python') Lb.insert(2, 'Java') Lb.insert(3, 'C++') Lb.insert(4, 'Any other') Lb.pack() top.mainloop() Output:
  8. MenuButton: It is a part of top-down menu which stays on the window all the time. Every menubutton has its own functionality. The general syntax is:w = MenuButton(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • activebackground: To set the background when mouse is over the widget.
    • activeforeground: To set the foreground when mouse is over the widget.
    • bg: to set he normal background color.
    • bd: to set the size of border around the indicator.
    • cursor: To appear the cursor when the mouse over the menubutton.
    • image: to set the image on the widget.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    • highlightcolor: To set the color of the focus highlight when widget has to be focused.
    filter_noneeditplay_arrowbrightness_4from tkinter import * top = Tk() mb =  Menubutton ( top, text = "GfG") mb.grid() mb.menu  =  Menu ( mb, tearoff = 0 ) mb["menu"]  =  mb.menu cVar  = IntVar() aVar = IntVar() mb.menu.add_checkbutton ( label ='Contact', variable = cVar ) mb.menu.add_checkbutton ( label = 'About', variable = aVar ) mb.pack() top.mainloop() Output:
  9. Menu: It is used to create all kinds of menus used by the application.
    The general syntax is:w = Menu(master, option=value) master is the parameter used to represent the parent window.There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • title: To set the title of the widget.
    • activebackground: to set the background color when widget is under the cursor.
    • activeforeground: to set the foreground color when widget is under the cursor.
    • bg: to set he normal background color.
    • command: to call a function.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import * root = Tk() menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='New') filemenu.add_command(label='Open...') filemenu.add_separator() filemenu.add_command(label='Exit', command=root.quit) helpmenu = Menu(menu) menu.add_cascade(label='Help', menu=helpmenu) helpmenu.add_command(label='About') mainloop() Output:
  10. Message: It refers to the multi-line and non-editable text. It works same as that of Label.
    The general syntax is:

    w = Message(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bd: to set the border around the indicator.
    • bg: to set he normal background color.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *main = Tk() ourMessage ='This is our Message'messageVar = Message(main, text = ourMessage) messageVar.config(bg='lightgreen') messageVar.pack( ) main.mainloop( ) Output:
  11. RadioButton: It is used to offer multi-choice option to the user. It offers several options to the user and the user has to choose one option.
    The general syntax is:w = RadioButton(master, option=value) There are number of options which are used to change the format of this widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • activebackground: to set the background color when widget is under the cursor.
    • activeforeground: to set the foreground color when widget is under the cursor.
    • bg: to set he normal background color.
    • command: to call a function.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    • width: to set the width of the label in characters.
    • height: to set the height of the label in characters.
    filter_noneeditplay_arrowbrightness_4from tkinter import *root = Tk() v = IntVar() Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W) Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W) mainloop() Output:
  12. Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax is:w = Scale(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • cursor: To change the cursor pattern when the mouse is over the widget.
    • activebackground: To set the background of the widget when mouse is over the widget.
    • bg: to set he normal background color.
    • orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
    • from_: To set the value of one end of the scale range.
    • to: To set the value of the other end of the scale range.
    • image: to set the image on the widget.
    • width: to set the width of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *master = Tk() w = Scale(master, from_=0, to=42) w.pack() w = Scale(master, from_=0, to=200, orient=HORIZONTAL) w.pack() mainloop() Output:
  13. Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
    The general syntax is:w = Scrollbar(master, option=value) master is the parameter used to represent the parent window. There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • width: to set the width of the widget.
    • activebackground: To set the background when mouse is over the widget.
    • bg: to set he normal background color.
    • bd: to set the size of border around the indicator.
    • cursor: To appear the cursor when the mouse over the menubutton.
    filter_noneeditplay_arrowbrightness_4from tkinter import *root = Tk() scrollbar = Scrollbar(root) scrollbar.pack( side = RIGHT, fill = Y ) mylist = Listbox(root, yscrollcommand = scrollbar.set ) for line in range(100): mylist.insert(END, 'This is line number' + str(line)) mylist.pack( side = LEFT, fill = BOTH ) scrollbar.config( command = mylist.yview ) mainloop() Output:
  14. Text: To edit a multi-line text and format the way it has to be displayed.
    The general syntax is:w =Text(master, option=value) There are number of options which are used to change the format of the text. Number of options can be passed as parameters separated by commas. Some of them are listed below.

    • highlightcolor: To set the color of the focus highlight when widget has to be focused.
    • insertbackground: To set the background of the widget.
    • bg: to set he normal background color.
    • font: to set the font on the button label.
    • image: to set the image on the widget.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *root = Tk() T = Text(root, height=2, width=30) T.pack() T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n') mainloop() Output:
  15. TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work on.The general syntax is:w = TopLevel(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bg: to set he normal background color.
    • bd: to set the size of border around the indicator.
    • cursor: To appear the cursor when the mouse over the menubutton.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *root = Tk() root.title('GfG') top = Toplevel() top.title('Python') top.mainloop() Output:
  16. SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The general syntax is:w = SpinBox(master, option=value) There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bg: to set he normal background color.
    • bd: to set the size of border around the indicator.
    • cursor: To appear the cursor when the mouse over the menubutton.
    • command: To call a function.
    • width: to set the width of the widget.
    • activebackground: To set the background when mouse is over the widget.
    • disabledbackground: To disable the background when mouse is over the widget.
    • from_: To set the value of one end of the range.
    • to: To set the value of the other end of the range.
    filter_noneeditplay_arrowbrightness_4from tkinter import *master = Tk() w = Spinbox(master, from_ = 0, to = 10) w.pack() mainloop() Output:
  17. PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general syntax is:w = PannedWindow(master, option=value) master is the parameter used to represent the parent window.
    There are number of options which are used to change the format of the widget. Number of options can be passed as parameters separated by commas. Some of them are listed below.
    • bg: to set he normal background color.
    • bd: to set the size of border around the indicator.
    • cursor: To appear the cursor when the mouse over the menubutton.
    • width: to set the width of the widget.
    • height: to set the height of the widget.
    filter_noneeditplay_arrowbrightness_4from tkinter import *m1 = PanedWindow() m1.pack(fill = BOTH, expand = 1) left = Entry(m1, bd = 5) m1.add(left) m2 = PanedWindow(m1, orient = VERTICAL) m1.add(m2) top = Scale( m2, orient = HORIZONTAL) m2.add(top) mainloop() Output:

This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Advantages of GUI

Graphical user interface plays an important role in computing. Whether it is a mobile app or any electronic or mechanical device we use, we see GUI (Graphical User Interface) all over in our daily life. Like in our cars we see LCD screens, TV, AC controllers etc.

If you use operating system then you may get alert window opens up on any error or for notification which is a type of user interface. So today I will provide some advantages and disadvantages of GUI.

Advantages of graphical user interface:-

Easiness for non-technical people:-

For non-technical people or for beginners good GUI’s tends to make easiness in life. For example with few clicks on buttons user can easily make his work done. Software in shops for calculation of products sold and inventory can be better managed by an even non-technical guy. Similarly listening songs in the car is easy for everyone.

Drag and drop feature:-

In most of the software, we have drag and drop functionality by which complex tasks are managed easily. Like dragging and dropping folders. And in mobile games, it is also nice to use. In much graphical software, drag and drop are awesome.

Looks nicer than text interface:-

In text interface, we have limited options to choose from and navigation is difficult. For non-educated people, text interface is difficult to understand and use. In GUI user can use any tool by detecting symbols or buttons.

Hotkeys usage:-

Sometimes we want a couple of functionality performed by single click then we use hotkeys. Like we see some buttons or mouse clicks/movements by which a couple of actions performed. This is very handy for speeding up tasks.

User-friendly:-

A user can easily navigate to the system without knowing a lot of details. Easy setup and ready to start working are awesome. Most of the software hides the complexity of actions from the users and display only required information is key to good interface.

Disabled people:-

In modern science, we can detect eyes movement and finger movement which is helpful for disabled people. Now, most of the software use this functionality to make life easier for disabled people. They can use software and websites easily with a few actions

Disadvantages of GUI

Difficult to develop and high cost:-

Nice looking designs are difficult to make and may also cost extra hardware support. Like high-quality games consume a lot of device space and memory and it also required very skilled people to develop.

Slower than command line tools:-

In command line tools like MS dos, we perform some commands which do the work quickly. But if we do the same task in GUI then it takes extra time to complete the task.

 Extra attention required:-

If we are driving a car then controlling music/radio in the car requires attention which makes our driving disturbed.

Using flat screen:-

Some graphical things do not display accurately on flat screens. In airplanes, sticks are used to control most of the things because flat screen display is not very handy. This makes the limitation of GUI.

Time consumption:-

It takes a lot of time to develop and design a good looking interface. If some bad interface builds then it makes difficult for the user to understand and use.

Memory resources:-

I see a lot of good GUI’s consuming lot of memory resources which make system/device slow to perform.

Implementation:-

Testing and implementation take a lot of time. Like we may require extra software for running GUI’s

Introduction to GUI library

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 − This is an open-source Python interface for wxWindows .
  • JPython − JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine h.

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

#!/usr/bin/python

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

This would create a following window −

TK 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
1ButtonThe Button widget is used to display buttons in your application.
2CanvasThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.
3CheckbuttonThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.
4EntryThe Entry widget is used to display a single-line text field for accepting values from a user.
5FrameThe Frame widget is used as a container widget to organize other widgets.
6LabelThe Label widget is used to provide a single-line caption for other widgets. It can also contain images.
7ListboxThe Listbox widget is used to provide a list of options to a user.
8MenubuttonThe Menubutton widget is used to display menus in your application.
9MenuThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.
10MessageThe Message widget is used to display multiline text fields for accepting values from a user.
11RadiobuttonThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.
12ScaleThe Scale widget is used to provide a slider widget.
13ScrollbarThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14TextThe Text widget is used to display text in multiple lines.
15ToplevelThe Toplevel widget is used to provide a separate window container.
16SpinboxThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.
17PanedWindowA PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically.
18LabelFrameA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.
19tkMessageBoxThis 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.

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.

The Root Window

To begin using the Tk API you open a root window. Tk applications can have more than one open window, but the main window is called the root window. It is opened by calling a function called Tk().

Example 6.1 Here is code to open a Tk window.

i m p o r t sys

i m p o r t tkinter

3

d e f main ():

5 root = tkinter.Tk()

6

7 root.title(“Reminder!”)

8 root.resizable(width=False ,height=False)

9

10 tkinter.mainloop ()

11

12 i f __name__ == “__main__”:

13 main ()

The code in Example 6.1 opens a window as pictured in Fig. 6.1. The call to the title method sets the title of the window. The call to resizable makes the window a non-resizable window. The Tkinter.mainloop() calls the Tk event dispatch loop to process events from the windowing application. Even with a simple window like this, the call to mainloop is required because there are events that even a simple

Fig. 6.1 A Tk root window

window must respond to. For example, when a window is moved on the screen it must respond to its redraw event. Redrawing the window is done automatically by the Tk code once the mainloop function is called.

Working With Containers:

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
1bgThe normal background color displayed behind the label and indicator.
2bdThe size of the border around the indicator. Default is 2 pixels.
3cursorIf 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.
4heightThe vertical dimension of the new frame.
5highlightbackgroundColor of the focus highlight when the frame does not have focus.
6highlightcolorColor shown in the focus highlight when the frame has the focus.
7highlightthicknessThickness of the focus highlight.
8reliefWith 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
9widthThe 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 −

TK Frame

Canvas

The Canvas widget provides structured graphics facilities for Tkinter. This is a highly versatile widget which can be used to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.

When to use the Canvas Widget #

The canvas is a general purpose widget, which is typically used to display and edit graphs and other drawings.

Another common use for this widget is to implement various kinds of custom widgets. For example, you can use a canvas as a completion bar, by drawing and updating a rectangle on the canvas.

Patterns #

To draw things in the canvas, use the create methods to add new items.

from Tkinter import *

master = Tk()

w = Canvas(master, width=200, height=100)
w.pack()

w.create_line(0, 0, 200, 100)
w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))

w.create_rectangle(50, 25, 150, 75, fill="blue")

mainloop()

Note that items added to the canvas are kept until you remove them. If you want to change the drawing, you can either use methods like coordsitemconfig, and move to modify the items, or use delete to remove them.

i = w.create_line(xy, fill="red")

w.coords(i, new_xy) # change coordinates
w.itemconfig(i, fill="blue") # change color

w.delete(i) # remove

w.delete(ALL) # remove all items

Concepts #

To display things on the canvas, you create one or more canvas items, which are placed in a stack. By default, new items are drawn on top of items already on the canvas.

Tkinter provides lots of methods allowing you to manipulate the items in various ways. Among other things, you can attach (bind) event callbacks to individual canvas items.

Canvas Items #

The Canvas widget supports the following standard items:

Chords, pieslices, ovals, polygons, and rectangles consist of both an outline and an interior area, either of which can be made transparent (and if you insist, you can make both transparent).

Window items are used to place other Tkinter widgets on top of the canvas; for these items, the Canvas widget simply acts like a geometry manager.

You can also write your own item types in C or C++ and plug them into Tkinter via Python extension modules.

Coordinate Systems #

The Canvas widget uses two coordinate systems; the window coordinate system (with (0, 0) in the upper left corner), and a canvas coordinate system which specify where the items are drawn. By scrolling the canvas, you can specify which part of the canvas coordinate system to show in the window.

The scrollregion option is used to limit scrolling operations for the canvas. To set this, you can usually use something like:

    canvas.config(scrollregion=canvas.bbox(ALL))

To convert from window coordinates to canvas coordinates, use the canvasxand canvasy methods:

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

Item Specifiers: Handles and Tags #

The Canvas widget allows you to identify items in several ways. Everywhere a method expects an item specifier, you can use one of the following:

  • item handles (integers)
  • tags
  • ALL
  • CURRENT

Item handles are integer values used to identify a specific item on the canvas. Tkinter automatically assigns a new handle to each new item created on the canvas. Item handles can be passed to the various canvas methods either as integers or as strings.

Tags are symbolic names attached to items. Tags are ordinary strings, and they can contain anything except whitespace (as long as they don’t look like item handles).

An item can have zero or more tags associated with it, and the same tag can be used for more than one item. However, unlike the Text widget, the Canvaswidget doesn’t allow you to create bindings or otherwise configure tags for which there are no existing items. Tags are owned by the items, not the widget itself. All such operations are ignored.

You can either specify the tags via an option when you create the item, set them via the itemconfig method, or add them using the addtag_withtag method. The tags option takes either a single tag string, or a tuple of strings.

item = canvas.create_line(0, 0, 100, 100, tags="uno")
canvas.itemconfig(item, tags=("one", "two"))
canvas.addtag_withtag("three", "one")

To get all tags associated with a specific item, use gettags. To get the handles for all items having a given tag, use find_withtag.

>>> print canvas.gettags(item)
('one', 'two', 'three')
>>> print canvas.find_withtag("one")
(1,)

The Canvas widget also provides two predefined tags:

ALL (or the string “all”) matches all items on the canvas.

CURRENT (or “current”) matches the item under the mouse pointer, if any. This can be used inside mouse event bindings to refer to the item that triggered the callback.

Printing #

The Tkinter widget supports printing to Postscript printers.

Performance Issues #

The Canvas widget implements a straight-forward damage/repair display model. Changes to the canvas, and external events such as Expose, are all treated as “damage” to the screen. The widget maintains a dirty rectangle to keep track of the damaged area.

When the first damage event arrives, the canvas registers an idle task (using after_idle) which is used to “repair” the canvas when the program gets back to the Tkinter main loop. You can force updates by calling the update_idletasksmethod.

When it’s time to redraw the canvas, the widget starts by allocating a pixmap (on X windows, this is an image memory stored on the display) with the same size as the dirty rectangle.

It then loops over the canvas items, and redraws all items for which the bounding box touch the dirty rectangle (this means that diagonal lines may be redrawn also if they don’t actually cover the rectangle, but this is usually no big deal).

Finally, the widget copies the pixmap to the display, and releases the pixmap. The copy operation is a very fast operation on most modern hardware.

Since the canvas uses a single dirty rectangle, you can sometimes get better performance by forcing updates. For example, if you’re changing things in different parts of the canvas without returning to the main loop, adding explicit calls to update_idletasks() allows the canvas to update a few small rectangles, instead of a large one with many more objects.

Reference #

Canvas(master=None, **options) (class) [#]

A structured graphics canvas.masterParent widget.**optionsWidget options. See the description of the config method for a list of available options.
addtag(tag, method, *args) [#]

Adds a tag to a number of items. Application code should use more specific methods wherever possible (that is, use addtag_aboveinstead of addtag(“above”), and so on.tagThe tag to add.methodHow to add a new tag. This can be one of “above”, “all”, “below”, “closest”, “enclosed”, “overlapping” or “withtag”.*argsAdditional arguments. For details, see the description of the individual method.
addtag_above(tag, item) [#]

Adds a tag to the item just above the given item.tagThe tag to add.itemThe tag or id of the reference item.
addtag_all(tag) [#]

Adds a tag to all items on the canvas. This is a shortcut foraddtag_withtag(newtag, ALL).tagThe tag to add.
addtag_below(tag, item) [#]

Adds a tag to the item just below the given item.tagThe tag to add.itemThe tag or id of the reference item.
addtag_closest(tag, x, y, halo=None, start=None) [#]

Adds a tag to the item closest to the given coordinate. Note that the position is given in canvas coordinates, and that this method always succeeds if there’s at least one item in the canvas. To add tags to items within a certain distance from the position, use add_overlapping(dead link) with a small rectangle centered on the position.tagThe tag to add.xThe horizontal coordinate.yThe vertical coordinate.haloOptional halo distance.startOptional start item.
addtag_enclosed(tag, x1, y1, x2, y2) [#]

Adds a tag to all items enclosed by the given rectangle.tagThe tag to add.x1Left coordinate.y1Top coordinate.x2Right coordinate.y2Bottom coordinate.
addtag_overlapped(tag, x1, y1, x2, y2) [#]

Adds a tag to all items overlapping the given rectangle. This includes items that are completely enclosed by it.tagThe tag to add.x1Left coordinate.y1Top coordinate.x2Right coordinate.y2Bottom coordinate.
addtag_withtag(tag, item) [#]

Adds a tag to all items having the given tag.tagThe tag to add.itemThe reference item. If a tag is given, the new tag is added to all items that have this tag. You can also give an id, to add a tag to a single item.
bbox(item=None) [#]

Returns the bounding box for all matching items. If the tag is omitted, the bounding box for all items is returned. Note that the bounding box is approximate and may differ a few pixels from the real value.itemItem specifier. If omitted, the bounding box for all elements on the canvas.Returns:The bounding box, as a 4-tuple.
canvasx(x, gridspacing=None) [#]

Converts a window coordinate to a canvas coordinate.xScreen coordinate.gridspacingOptional grid spacing. The coordinate is rounded to the nearest grid coordinate.Returns:Canvas coordinate.
canvasy(y, gridspacing=None) [#]

Converts a window coordinate to a canvas coordinate.yScreen coordinate.gridspacingOptional grid spacing. The coordinate is rounded to the nearest grid coordinate.Returns:Canvas coordinate.
config(**options) [#]

Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.**optionsWidget options.background=Canvas background color. Defaults to the standard widget background color. (the database name is background, the class is Background)bg=Same as background.borderwidth=Width of the canvas border. The default is 0 (no border). (borderWidth/BorderWidth)bd=Same as borderwidth.closeenough=The default value is 1. (closeEnough/CloseEnough)confine=The default value is 1. (confine/Confine)cursor=The cursor to use when the mouse is moved over the canvas. (cursor/Cursor)height=Canvas width. Default value is ‘7c’. (height/Height)highlightbackground=The color to use for the highlight border when the canvas does not have focus. The default is system specific. (highlightBackground/HighlightBackground)highlightcolor=The color to use for the highlight border when the canvas has focus. The default is system speciific. (highlightColor/HighlightColor)highlightthickness=The width of the highlight border. The default is system specific (usually one or two pixels). (highlightThickness/HighlightThickness)insertbackground=The color to use for the text insertion cursor. The default is system specific. (insertBackground/Foreground)insertborderwidth=Width of the insertion cursor’s border. If this is set to a non-zero value, the cursor is drawn using the RAISED border style. (insertBorderWidth/BorderWidth)insertofftime=Together with insertontime, this option controls cursor blinking. Both values are given in milliseconds. (insertOffTime/OffTime)insertontime=See insertofftime. (insertOnTime/OnTime)insertwidth=Width of the insertion cursor. Usually one or two pixels. (insertWidth/InsertWidth)offset=Default value is ‘0,0’. (offset/Offset)relief=Border style. The default is FLAT. Other possible values are SUNKENRAISEDGROOVE, and RIDGE. (relief/Relief)scrollregion=Canvas scroll region. No default value. (scrollRegion/ScrollRegion)selectbackground=Selection background color. The default is system and display specific. (selectBackground/Foreground)selectborderwidth=Selection border width. The default is system specific. (selectBorderWidth/BorderWidth)selectforeground=Selection text color. The default is system specific. (selectForeground/Background)state=Canvas state. One of NORMAL, DISABLED, or HIDDEN. The default is NORMAL. Note that this is a global setting, but individual canvas items can use the item-level state option to override this setting. (state/State)takefocus=Indicates that the user can use the Tab key to move to this widget. Default is an empty string, which means that the canvas widget accepts focus only if it has any keyboard bindings. (takeFocus/TakeFocus)width=Canvas width. Default value is ‘10c’. (width/Width)xscrollcommand=Used to connect a canvas to a horizontal scrollbar. This option should be set to the set method of the corresponding scrollbar. (xScrollCommand/ScrollCommand)xscrollincrement=Default value is 0. (xScrollIncrement/ScrollIncrement)yscrollcommand=Used to connect a canvas to a vertical scrollbar. This option should be set to the set method of the corresponding scrollbar. (yScrollCommand/ScrollCommand)yscrollincrement=Default value is 0. (yScrollIncrement/ScrollIncrement)
coords(item, *coords) [#]

Returns the coordinates for an item.itemItem specifier (tag or id).*coordsOptional list of coordinate pairs. If given, the coordinates will replace the current coordinates for all matching items.Returns:If no coordinates are given, this method returns the coordinates for the matching item. If the item specifier matches more than one item, the coordinates for the first item found is returned.
create_arc(bbox, **options) [#]

Draws an arc, pieslice, or chord on the canvas. The new item is drawn on top of the existing items.bboxBounding box for the full arc.**optionsArc options.activedash=activefill=Fill color to use when the mouse pointer is moved over the item, if different from fill.activeoutline=activeoutlinestipple=activestipple=activewidth=Default is 0.0.dash=Outline dash pattern, given as a list of segment lengths. Only the odd segments are drawn.dashoffset=Default is 0.disableddash=disabledfill=Fill color to use when the item is disabled, if different from fill.disabledoutline=disabledoutlinestipple=disabledstipple=disabledwidth=Default is 0.0.extent=The size, relative to the start angle. Default is 90.0.fill=Fill color. An empty string means transparent.offset=Default is “0,0”.outline=Outline color. Default is “black”.outlineoffset=Default is “0,0”.outlinestipple=Outline stipple pattern.start=Start angle. Default is 0.0.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.style=One of PIESLICE, CHORD, or ARC. Default is PIESLICE.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Default is 1.0.Returns:The item id.
create_bitmap(position, **options) [#]

Draws a bitmap on the canvas.positionBitmap position, given as two coordinates.**optionsBitmap options.activebackground=activebitmap=activeforeground=anchor=Where to place the bitmap relative to the given position. Default is CENTER.background=Background color, used for pixels that are “off”. Use an empty string to make the background transparent. Default is transparent.bitmap=The bitmap descriptor. See BitmapImage for more information. (To display a BitmapImage object, use the create_image function.)disabledbackground=disabledbitmap=disabledforeground=foreground=Foreground colors, used for pixels that are “on”. Default is “black”.state=Item state. One of NORMAL, DISABLED, or HIDDEN.tags=A tag to attach to this item, or a tuple containing multiple tags.Returns:The item id.
create_image(position, **options) [#]

Draws an image on the canvas.positionImage position, given as two coordinates.**optionsImage options.activeimage=anchor=Where to place the image relative to the given position. Default is CENTER.disabledimage=image=The image object. This should be a PhotoImage orBitmapImage, or a compatible object (such as the PIL PhotoImage). The application must keep a reference to the image object.state=Item state. One of NORMAL, DISABLED, or HIDDEN.tags=A tag to attach to this item, or a tuple containing multiple tags.Returns:The item id.
create_line(coords, **options) [#]

Draws a line on the canvas.coordsImage coordinates.**optionsLine options.activedash=activefill=Line color to use when the mouse pointer is moved over the item, if different from fill.activestipple=activewidth=Default is 0.0.arrow=Default is NONE.arrowshape=Default is “8 10 3”.capstyle=Default is BUTT.dash=Dash pattern, given as a list of segment lengths. Only the odd segments are drawn.dashoffset=Default is 0.disableddash=disabledfill=Line color to use when the item is disabled, if different from fill.disabledstipple=disabledwidth=Default is 0.0.fill=Line color. Default is “black”.joinstyle=Default is ROUND.offset=Default is “0,0”.smooth=Default is 0.splinesteps=Default is 12.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Default is 1.0.Returns:The item id.
create_oval(bbox, **options) [#]

Draws an ellipse on the canvas.bboxEllipse coordinates.**optionsEllipse options.activedash=activefill=Fill color to use when the mouse pointer is moved over the item, if different from fill.activeoutline=activeoutlinestipple=activestipple=activewidth=Default is 0.0.dash=Outline dash pattern, given as a list of segment lengths. Only the odd segments are drawn.dashoffset=Default is 0.disableddash=disabledfill=Fill color to use when the item is disabled, if different from fill.disabledoutline=disabledoutlinestipple=disabledstipple=disabledwidth=Default is 0.fill=Fill color. An empty string means transparent.offset=Default is “0,0”.outline=Outline color. Default is “black”.outlineoffset=Default is “0,0”.outlinestipple=Outline stipple pattern.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Default is 1.0.Returns:The item id.
create_polygon(coords, **options) [#]

Draws a polygon on the canvas.coordsPolygon coordinates.**optionsPolygon options.activedash=activefill=Fill color to use when the mouse pointer is moved over the item, if different from fill.activeoutline=activeoutlinestipple=activestipple=activewidth=Default is 0.0.dash=Outline dash pattern, given as a list of segment lengths. Only the odd segments are drawn.dashoffset=Default is 0.disableddash=disabledfill=Fill color to use when the item is disabled, if different from fill.disabledoutline=disabledoutlinestipple=disabledstipple=disabledwidth=Default is 0.0.fill=Fill color. Default is “black”.joinstyle=Default is ROUND.offset=Default is “0,0”.outline=Outline color.outlineoffset=Default is “0,0”.outlinestipple=Outline stipple pattern.smooth=Default is 0.splinesteps=Default is 12.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Default is 1.0.Returns:The item id.
create_rectangle(bbox, **options) [#]

Draws a rectangle on the canvas.bboxRectangle bounding box.**optionsRectangle options.activedash=activefill=Fill color to use when the mouse pointer is moved over the item, if different from fill.activeoutline=activeoutlinestipple=activestipple=activewidth=Default is 0.0.dash=Outline dash pattern, given as a list of segment lengths. Only the odd segments are drawn.dashoffset=Default is 0.disableddash=disabledfill=Fill color to use when the item is disabled, if different from fill.disabledoutline=disabledoutlinestipple=disabledstipple=disabledwidth=Default is 0.fill=Fill color. An empty string means transparent.offset=Default is “0,0”.outline=Outline color. Default is “black”.outlineoffset=Default is “0,0”.outlinestipple=Outline stipple pattern.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Default is 1.0.Returns:The item id.
create_text(position, **options) [#]

Draws text on the canvas.positionText position, given as two coordinates. By default, the text is centered on this position. You can override this with the anchor option. For example, if the coordinate is the upper left corner, set the anchor to NW.**optionsText options.activefill=Text color to use when the mouse pointer is moved over the item, if different from fill.activestipple=anchor=Where to place the text relative to the given position. Default is CENTER.disabledfill=Text color to use when the item is disabled, if different from fill.disabledstipple=fill=Text color. Default is “black”.font=Font specifier. Default is system specific.justify=Default is LEFT.offset=Default is “0,0”.state=Item state. One of NORMAL, DISABLED, or HIDDEN.stipple=Stipple pattern.tags=A tag to attach to this item, or a tuple containing multiple tags.text=The text to display.width=Maximum line length. Lines longer than this value are wrapped. Default is 0 (no wrapping).Returns:The item id.
create_window(position, **options) [#]

Places a Tkinter widget on the canvas. Note that widgets are drawn on top of the canvas (that is, the canvas acts like a geometry manager). You cannot draw other canvas items on top of a widget.positionWindow position, given as two coordinates.**optionsWindow options.anchor=Where to place the widget relative to the given position. Default is CENTER.height=Window height. Default is to use the window’s requested height.state=Item state. One of NORMAL, DISABLED, or HIDDEN.tags=A tag to attach to this item, or a tuple containing multiple tags.width=Window width. Default is to use the window’s requested width.window=Window object.Returns:The item id.
dchars(item, from, to=None) [#]

Deletes text from an editable item.itemItem specifier.fromWhere to start deleting text.toWhere to stop deleting text. If omitted, a single character is removed.
delete(item) [#]

Deletes all matching items. It is not an error to give an item specifier that doesn’t match any items.itemItem specifier (tag or id).
dtag(item, tag=None) [#]

Removes the given tag from all matching items. If the tag is omitted, all tags are removed from the matching items. It is not an error to give a specifier that doesn’t match any items.itemThe item specifier (tag or id).tagThe tag to remove from matching items. If omitted, all tags are removed.
find_above(item) [#]

Returns the item just above the given item.itemReference item.
find_all() [#]

Returns all items on the canvas. This method returns a tuple containing the identities of all items on the canvas, with the topmost item last (that is, if you haven’t change the order using lift or lower, the items are returned in the order you created them). This is shortcut for find_withtag(ALL).Returns:A tuple containing all items on the canvas.
find_below(item) [#]

Returns the item just below the given item.itemReference item.
find_closest(x, y, halo=None, start=None) [#]

Returns the item closest to the given position. Note that the position is given in canvas coordinates, and that this method always succeeds if there’s at least one item in the canvas. To find items within a certain distance from a position, use find_overlapping with a small rectangle centered on the position.xHorizontal screen coordinate.yVertical screen coordinate.haloOptional halo distance.startOptional start item.Returns:An item specifier.
find_enclosed(x1, y1, x2, y2) [#]

Finds all items completely enclosed by the rectangle (x1, y1, x2, y2).x1Left edge.y1Upper edge.x2Right edge.y2Lower edge.Returns:A tuple containing all matching items.
find_overlapping(x1, y1, x2, y2) [#]

Finds all items that overlap the given rectangle, or that are completely enclosed by it.x1Left edge.y1Upper edge.x2Right edge.y2Lower edge.Returns:A tuple containing all matching items.
find_withtag(item) [#]

Finds all items having the given specifier.itemItem specifier.
focus(item=None) [#]

Moves focus to the given item. If the item has keyboard bindings, it will receive all further keyboard events, given that the canvas itself also has focus. It’s usually best to call focus_set on the canvas whenever you set focus to a canvas item.

To remove focus from the item, call this method with an empty string.

To find out what item that currently has focus, call this method without any arguments.itemItem specifier. To remove focus from any item, use an empty string.Returns:If the item specifier is omitted, this method returns the item that currently has focus, or None if no item has focus.
gettags(item) [#]

Gets tags associated with an item.itemItem specifier.Returns:A tuple containing all tags associated with the item.
icursor(item, index) [#]

Moves the insertion cursor to the given position. This method can only be used with editable items.itemItem specifier.indexCursor index.
index(item, index) [#]

Gets the numerical cursor index corresponding to the given index. Numerical indexes work like Python’s sequence indexes; 0 is just to the left of the first character, and len(text) is just to the right of the last character.itemItem specifier.indexAn index. You can use a numerical index, or one of INSERT (the current insertion cursor), END (the length of the text), or SEL_FIRST and SEL_LAST (the selection start and end). You can also use the form “@x,y” where x and y are canvas coordinates, to get the index closest to the given coordinate.Returns:A numerical index (an integer).
insert(item, index, text) [#]

Inserts text into an editable item.itemItem specifier.indexWhere to insert the text. This can be either a numerical index or a symbolic constant. See the description of the indexmethod for details. If you insert text at the INSERT index, the cursor is moved along with the text.textThe text to insert.
itemcget(item, option) [#]

Gets the current value for an item option.itemItem specifier.optionItem option.Returns:The option value. If the item specifier refers to more than one item, this method returns the option value for the first item found.
itemconfig(item, **options) [#]

Changes one or more options for all matching items.itemItem specifier.**optionsItem options.
itemconfigure(item, **options) [#]

Same as itemconfig.lift(item, **options) [#]

(Deprecated) Moves item to top of stack. Same as tag_raise.lower(item, **options) [#]

(Deprecated) Moves item to bottom of stack. Same as tag_lower.move(item, dx, dy) [#]

Moves matching items by an offset.itemItem specifier.dxHorizontal offset.dyVertical offset.
postscript(**options) [#]

Generates a Postscript rendering of the canvas contents. Images and embedded widgets are not included.**optionsPostscript options.
scale(self, xscale, yscale, xoffset, yoffset) [#]

Resizes matching items by scale factor. The coordinates for each item are recalculated as ((coord-offset)*scale+offset); in other words, each item first moved by -offset, then multiplied with the scale factor, and then moved back again. Note that this method modifies the item coordinates; you may loose precision if you use this method several times on the same items.xscaleHorizontal scale.yscaleVertical scale.xoffsetHorizontal offset, in canvas coordinates.yoffsetVertical scale, in canvas coordinates.
scan_dragto(x, y) [#]

Scrolls the widget contents relative to the scanning anchor. The contents are moved 10 times the distance between the anchor and the given position. Use scan_mark to set the anchor.xThe horizontal coordinate.yThe vertical coordinate.
scan_mark(x, y) [#]

Sets the scanning anchor. This sets an anchor that can be used for fast scrolling to the given mouse coordinate.xThe horizontal coordinate.yThe vertical coordinate.
select_adjust(item, index) [#]

Adjusts the selection, so that it includes the given index. This method also sets the selection anchor to this position. This is typically used by mouse bindings.itemItem specifier.indexSelection index.
select_clear() [#]

Removes the selection, if it is in this canvas widget.select_from(item, index) [#]

Sets the selection anchor point. Use select_adjust or select_to to extend the selection.itemItem specifier.indexSelection anchor.
select_item() [#]

Returns the item that owns the text selection for this canvas widget.

Note that this method always returns None in some older versions of Tkinter. To work around this problem, replace the method call with canvas.tk.call(canvas._w, “select”, “item”).Returns:Item specifier, or None if there’s no selection.
select_to(item, index) [#]

Modifies the selection so it includes the region between the current selection anchor and the given index. The anchor is set by select_from or select_adjust.itemItem specifier.indexSelection end point.
tag_bind(item, event=None, callback, add=None) [#]

Adds an event binding to all matching items.

Note that the new bindings are associated with the items, not the tag. For example, if you attach bindings to all items having the movabletag, they will only be attached to any existing items with that tag. If you create new items tagged as movable, they will not get those bindings.itemThe item specifier (tag or id).eventThe event specifier.callbackA callable object that takes one argument. This callback is called with an event descriptor, for events matching the given event specifier.addUsually, the new binding replaces any existing binding for the same event sequence. If this argument is present, and set to “+”, the new binding is added to to any existing binding.
tag_lower(item) [#]

Moves a canvas item to the bottom of the canvas stack. If multiple items match, they are all moved, with their relative order preserved.

This method doesn’t work with window items. To change their order, use lower on the widget instance instead.itemItem specifier.
tag_raise(item) [#]

Moves the given item to the top of the canvas stack. If multiple items match, they are all moved, with their relative order preserved.

This method doesn’t work with window items. To change their order, use lift on the widget instance instead.itemItem specifier.
tag_unbind(self, item, event) [#]

Removes the binding, if any, for the given event sequence. This applies to all matching items.itemItem specifier.sequenceEvent specifier.
tkraise(item, **options) [#]

(Deprecated) Same as tag_raise.type(item) [#]

Returns the type of the given item. If item refers to more than one item, this method returns the type of the first item found.itemItem specifier.Returns:A string, giving the item type. This can be one of “arc”“bitmap”“image”“line”“oval”“polygon”“rectangle”“text”, or “window”.
xview(how, *args) [#]

Adjusts the canvas view horizontally.howHow to adjust the canvas. This can be either “moveto” or “scroll”.*argsAdditional arguments. For the “moveto” method, this is a single fraction. For the “scroll” method, this is a unit and a count. For details, see the descriptions of the xview_movetoand xview_scroll methods.
xview_moveto(fraction) [#]

Adjusts the canvas so that the given offset is at the left edge of the canvas.fractionScroll offset. Offset 0.0 is the beginning of the scrollregion, 1.0 the end.
xview_scroll(number, what) [#]

Scrolls the canvas horizontally by the given amount.numberNumber of units.whatWhat unit to use. This can be either “units” (small steps) or “pages”.
yview(how, *args) [#]

Adjusts the canvas view vertically.howHow to adjust the canvas. This can be either “moveto” or “scroll”.*argsAdditional arguments. For the “moveto” method, this is a single fraction. For the “scroll” method, this is a unit and a count. For details, see the descriptions of the yview_movetoand yview_scroll methods.
yview_moveto(fraction) [#]

Adjusts the canvas so that the given offset is at the top edge of the canvas.fractionScroll offset. Offset 0.0 is the beginning of the scrollregion, 1.0 the end.
yview_scroll(number, what) [#]

Scrolls the canvas vertically by the given amount.numberNumber of units.whatWhat unit to use. This can be either “units” (small steps) or “pages”.

Layout Management

 Tkinter possess three layout managers:

  • pack
  • grid
  • place

The three layout managers pack, grid, and place should never be mixed in the same master window! Geometry managers serve various functions. They:

  • arrange widgets on the screen
  • register widgets with the underlying windowing system
  • manage the display of widgets on the screen

Arranging widgets on the screen includes determining the size and position of components. Widgets can provide size and alignment information to geometry managers, but the geometry managers has always the final say on the positioning and sizing. 

Pack

Pack is the easiest to use of the three geometry managers of Tk and Tkinter. Instead of having to declare precisely where a widget should appear on the display screen, we can declare the positions of widgets with the pack command relative to each other. The pack command takes care of the details. Though the pack command is easier to use, this layout managers is limited in its possibilities compared to the grid and place mangers. For simple applications it is definitely the manager of choice. For example simple applications like placing a number of widgets side by side, or on top of each other. 

Example: 

from Tkinter import *

root = Tk()

Label(root, text="Red Sun", bg="red", fg="white").pack()
Label(root, text="Green Grass", bg="green", fg="black").pack()
Label(root, text="Blue Sky", bg="blue", fg="white").pack()

mainloop()
Packing some labels

fill Option

In our example, we have packed three labels into the parent widget “root”. We used pack() without any options. So pack had to decide which way to arrange the labels. As you can see, it has chosen to place the label widgets on top of each other and centre them. Furthermore, we can see that each label has been given the size of the text. If you want to make the widgets as wide as the parent widget, you have to use the fill=X option: 

from Tkinter import *

root = Tk()

w = Label(root, text="Red Sun", bg="red", fg="white")
w.pack(fill=X)
w = Label(root, text="Green Grass", bg="green", fg="black")
w.pack(fill=X)
w = Label(root, text="Blue Sky", bg="blue", fg="white")
w.pack(fill=X)

mainloop()
Packing labels and filling horizontally

Padding

The pack() manager knows four padding options, i.e. internal and external padding and padding in x and y direction: 

padxExternal padding, horizontally 

 

The code for the window above: 
from Tkinter import * root = Tk() w = Label(root, text=”Red Sun”, bg=”red”, fg=”white”) w.pack(fill=X,padx=10) w = Label(root, text=”Green Grass”, bg=”green”, fg=”black”) w.pack(fill=X,padx=10) w = Label(root, text=”Blue Sky”, bg=”blue”, fg=”white”) w.pack(fill=X,padx=10) mainloop()
padyExternal padding, vertically

 

The code for the window above: 
from Tkinter import * root = Tk() w = Label(root, text=”Red Sun”, bg=”red”, fg=”white”) w.pack(fill=X,pady=10) w = Label(root, text=”Green Grass”, bg=”green”, fg=”black”) w.pack(fill=X,pady=10) w = Label(root, text=”Blue Sky”, bg=”blue”, fg=”white”) w.pack(fill=X,pady=10) mainloop()
ipadxInternal padding, horizontally. 

In the following example, we change only the label with the text “Green Grass”, so that the result can be easier recognized. We have also taken out the fill option. 

 

from Tkinter import * root = Tk() w = Label(root, text=”Red Sun”, bg=”red”, fg=”white”) w.pack() w = Label(root, text=”Green Grass”, bg=”green”, fg=”black”) w.pack(ipadx=10) w = Label(root, text=”Blue Sky”, bg=”blue”, fg=”white”) w.pack() mainloop()
ipadyInternal padding, vertically 

We will change the last label of our previous example to ipady=10. 

 

from Tkinter import * root = Tk() w = Label(root, text=”Red Sun”, bg=”red”, fg=”white”) w.pack() w = Label(root, text=”Green Grass”, bg=”green”, fg=”black”) w.pack(ipadx=10) w = Label(root, text=”Blue Sky”, bg=”blue”, fg=”white”) w.pack(ipady=10) mainloop()

The default value in all cases is 0. 

Placing widgets side by side

We want to place the three label side by side now and shorten the text slightly: 

Packing labels side by side

The corresponding code looks like this: 

from Tkinter import *

root = Tk()

w = Label(root, text="red", bg="red", fg="white")
w.pack(padx=5, pady=10, side=LEFT)
w = Label(root, text="green", bg="green", fg="black")
w.pack(padx=5, pady=20, side=LEFT)
w = Label(root, text="blue", bg="blue", fg="white")
w.pack(padx=5, pady=20, side=LEFT)

mainloop()

If we change LEFT to RIGHT in the previous example, we get the colours in reverse order: 

Packing labels side by side right

Place Geometry Manager

The Place geometry manager allows you explicitly set the position and size of a window, either in absolute terms, or relative to another window. The place manager can be accessed through the place method. It can be applied to all standard widgets. 

We use the place geometry manager in the following example. We are playing around with colours in this example, i.e. we assign to every label a different colour, which we randomly create using the randrange method of the random module. We calculate the brightness (grey value) of each colour. If the brightness is less than 120, we set the foreground colour (fg) of the label to White otherwise to black, so that the text can be easier read. 

import Tkinter as tk
import random
    
root = tk.Tk()
# width x height + x_offset + y_offset:
root.geometry("170x200+30+30") 
     
languages = ['Python','Perl','C++','Java','Tcl/Tk']
labels = range(5)
for i in range(5):
   ct = [random.randrange(256) for x in range(3)]
   brightness = int(round(0.299*ct[0] + 0.587*ct[1] + 0.114*ct[2]))
   ct_hex = "%02x%02x%02x" % tuple(ct)
   bg_colour = '#' + "".join(ct_hex)
   l = tk.Label(root, 
                text=languages[i], 
                fg='White' if brightness < 120 else 'Black', 
                bg=bg_colour)
   l.place(x = 20, y = 30 + i*30, width=120, height=25)
          
root.mainloop()
example place geometry manager

Events and Bindings

As was mentioned earlier, a Tkinter application spends most of its time inside an event loop (entered via the mainloop method). Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager (indirectly caused by the user, in many cases).

Tkinter provides a powerful mechanism to let you deal with events yourself. For each widget, you can bind Python functions and methods to events.

widget.bind(event, handler)

If an event matching the event description occurs in the widget, the given handler is called with an object describing the event.

Here’s a simple example:Capturing clicks in a window

from Tkinter import *

root = Tk()

def callback(event):
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

In this example, we use the bind method of the frame widget to bind a callback function to an event called <Button-1>. Run this program and click in the window that appears. Each time you click, a message like “clicked at 44 63” is printed to the console window.

Keyboard events are sent to the widget that currently owns the keyboard focus. You can use the focus_set method to move focus to a widget:Capturing keyboard events

from Tkinter import *

root = Tk()

def key(event):
    print "pressed", repr(event.char)

def callback(event):
    frame.focus_set()
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

If you run this script, you’ll find that you have to click in the frame before it starts receiving any keyboard events.

Events #

Events are given as strings, using a special event syntax:

<modifier-type-detail>

The type field is the most important part of an event specifier. It specifies the kind of event that we wish to bind, and can be user actions like Button, and Key, or window manager events like EnterConfigure, and others. The modifier and detail fields are used to give additional information, and can in many cases be left out. There are also various ways to simplify the event string; for example, to match a keyboard key, you can leave out the angle brackets and just use the key as is. Unless it is a space or an angle bracket, of course.

Instead of spending a few pages on discussing all the syntactic shortcuts, let’s take a look on the most common event formats:

Event Formats

<Button-1>

A mouse button is pressed over the widget. Button 1 is the leftmost button, button 2 is the middle button (where available), and button 3 the rightmost button. When you press down a mouse button over a widget, Tkinter will automatically “grab” the mouse pointer, and subsequent mouse events (e.g. Motion and Release events) will then be sent to the current widget as long as the mouse button is held down, even if the mouse is moved outside the current widget. The current position of the mouse pointer (relative to the widget) is provided in the x and y members of the event object passed to the callback.

You can use ButtonPress instead of Button, or even leave it out completely: <Button-1><ButtonPress-1>, and <1> are all synonyms. For clarity, I prefer the <Button-1> syntax.<B1-Motion>

The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button). The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.<ButtonRelease-1>

Button 1 was released. The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.<Double-Button-1>

Button 1 was double clicked. You can use Double or Triple as prefixes. Note that if you bind to both a single click (<Button-1>) and a double click, both bindings will be called.<Enter>

The mouse pointer entered the widget (this event doesn’t mean that the user pressed the Enter key!).<Leave>

The mouse pointer left the widget.<FocusIn>

Keyboard focus was moved to this widget, or to a child of this widget.<FocusOut>

Keyboard focus was moved from this widget to another widget.<Return>

The user pressed the Enter key. You can bind to virtually all keys on the keyboard. For an ordinary 102-key PC-style keyboard, the special keys are Cancel (the Break key), BackSpaceTabReturn(the Enter key), Shift_L (any Shift key), Control_L (any Control key), Alt_L(any Alt key), PauseCaps_LockEscapePrior (Page Up), Next(Page Down), EndHomeLeftUpRightDownPrintInsert,DeleteF1F2F3F4F5F6F7F8F9F10F11F12Num_Lock, and Scroll_Lock.<Key>

The user pressed any key. The key is provided in the char member of the event object passed to the callback (this is an empty string for special keys).a

The user typed an “a”. Most printable characters can be used as is. The exceptions are space (<space>) and less than (<less>). Note that 1 is a keyboard binding, while <1> is a button binding.<Shift-Up>

The user pressed the Up arrow, while holding the Shift key pressed. You can use prefixes like AltShift, and Control.<Configure>

The widget changed size (or location, on some platforms). The new size is provided in the width and height attributes of the event object passed to the callback.

The Event Object

The event object is a standard Python object instance, with a number of attributes describing the event.

Event Attributes

widget

The widget which generated this event. This is a valid Tkinter widget instance, not a name. This attribute is set for all events.x, y

The current mouse position, in pixels.x_root, y_root

The current mouse position relative to the upper left corner of the screen, in pixels.char

The character code (keyboard events only), as a string.keysym

The key symbol (keyboard events only).keycode

The key code (keyboard events only).num

The button number (mouse button events only).width, height

The new size of the widget, in pixels (Configure events only).type

The event type.

For portability reasons, you should stick to charheightwidthxyx_root,y_root, and widget. Unless you know exactly what you’re doing, of course…

Instance and Class Bindings

The bind method we used in the above example creates an instance binding. This means that the binding applies to a single widget only; if you create new frames, they will not inherit the bindings.

But Tkinter also allows you to create bindings on the class and application level; in fact, you can create bindings on four different levels:

  • the widget instance, using bind.
  • the widget’s toplevel window (Toplevel or root), also using bind.
  • the widget class, using bind_class (this is used by Tkinter to provide standard bindings).
  • the whole application, using bind_all.

For example, you can use bind_all to create a binding for the F1 key, so you can provide help everywhere in the application. But what happens if you create multiple bindings for the same key, or provide overlapping bindings?

First, on each of these four levels, Tkinter chooses the “closest match” of the available bindings. For example, if you create instance bindings for the <Key>and <Return> events, only the second binding will be called if you press the Enter key.

However, if you add a <Return> binding to the toplevel widget, both bindings will be called. Tkinter first calls the best binding on the instance level, then the best binding on the toplevel window level, then the best binding on the class level (which is often a standard binding), and finally the best available binding on the application level. So in an extreme case, a single event may call four event handlers.

A common cause of confusion is when you try to use bindings to override the default behavior of a standard widget. For example, assume you wish to disable the Enter key in the text widget, so that the users cannot insert newlines into the text. Maybe the following will do the trick?

def ignore(event):
    pass
text.bind("<Return>", ignore)

or, if you prefer one-liners:

text.bind("<Return>", lambda e: None)

(the lambda function used here takes one argument, and returns None)

Unfortunately, the newline is still inserted, since the above binding applies to the instance level only, and the standard behavior is provided by a class level bindings.

You could use the bind_class method to modify the bindings on the class level, but that would change the behavior of all text widgets in the application. An easier solution is to prevent Tkinter from propagating the event to other handlers; just return the string “break” from your event handler:

def ignore(event):
    return "break"
text.bind("<Return>", ignore)

or

text.bind("<Return>", lambda e: "break")

By the way, if you really want to change the behavior of all text widgets in your application, here’s how to use the bind_class method:

top.bind_class("Text", "<Return>", lambda e: None)

But there are a lot of reasons why you shouldn’t do this. For example, it messes things up completely the day you wish to extend your application with some cool little UI component you downloaded from the net. Better use your own Textwidget specialization, and keep Tkinter’s default bindings intact:

class MyText(Text):
    def __init__(self, master, **kw):
        apply(Text.__init__, (self, master), kw)
        self.bind("<Return>", lambda e: "break")

Protocols #

In addition to event bindings, Tkinter also supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager.

You can use the protocol method to install a handler for this protocol (the widget must be a root or Toplevel widget):

widget.protocol("WM_DELETE_WINDOW", handler)

Once you have installed your own handler, Tkinter will no longer automatically close the window. Instead, you could for example display a message box asking the user if the current data should be saved, or in some cases, simply ignore the request. To close the window from this handler, simply call the destroy method of the window:Capturing destroy events

from Tkinter import *
import tkMessageBox

def callback():
    if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
        root.destroy()

root = Tk()
root.protocol("WM_DELETE_WINDOW", callback)

root.mainloop()

Note that even you don’t register an handler for WM_DELETE_WINDOWon a toplevel window, the window itself will be destroyed as usual (in a controlled fashion, unlike X). However, as of Python 1.5.2, Tkinter will not destroy the corresponding widget instance hierarchy, so it is a good idea to always register a handler yourself:

top = Toplevel(...)

# make sure widget instances are deleted
top.protocol("WM_DELETE_WINDOW", top.destroy)

Future versions of Tkinter will most likely do this by default.

Other Protocols

Window manager protocols were originally part of the X window system (they are defined in a document titled Inter-Client Communication Conventions Manual, or ICCCM). On that platform, you can install handlers for other protocols as well, like WM_TAKE_FOCUS and WM_SAVE_YOURSELF. See the ICCCM documentation for details.

Font

There may be up to three ways to specify type style.

Simple Tuple Fonts

As a tuple whose first element is the font family, followed by a size in points, optionally followed by a string containing one or more of the style modifiers bold, italic, underline and overstrike.

Example

  • (“Helvetica”, “16”) for a 16-point Helvetica regular.
  • (“Times”, “24”, “bold italic”) for a 24-point Times bold italic.

Font object Fonts

You can create a “font object” by importing the tkFont module and using its Font class constructor −

import tkFont

font = tkFont.Font ( option, ... )

Here is the list of options −

  • family − The font family name as a string.
  • size − The font height as an integer in points. To get a font n pixels high, use -n.
  • weight − “bold” for boldface, “normal” for regular weight.
  • slant − “italic” for italic, “roman” for unslanted.
  • underline − 1 for underlined text, 0 for normal.
  • overstrike − 1 for overstruck text, 0 for normal.

Example

helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")

X Window Fonts

If you are running under the X Window System, you can use any of the X font names.

For example, the font named “-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*” is the author’s favorite fixed-width font for onscreen use. Use the xfontsel program to help you select pleasing fonts.

colors

For a visual representation of the matplotlib colormaps, see the “Color” section in the gallery.

matplotlib.colors

A module for converting numbers or color arguments to RGB or RGBA

RGB and RGBA are sequences of, respectively, 3 or 4 floats in the range 0-1.

This module includes functions and classes for color specification conversions, and for mapping numbers to colors in a 1-D array of colors called a colormap. Colormapping typically involves two steps: a data array is first mapped onto the range 0-1 using an instance of Normalize or of a subclass; then this number in the 0-1 range is mapped to a color using an instance of a subclass of Colormap. Two are provided here: LinearSegmentedColormap, which is used to generate all the built-in colormap instances, but is also useful for making custom colormaps, andListedColormap, which is used for generating a custom colormap from a list of color specifications.

The module also provides functions for checking whether an object can be interpreted as a color (is_color_like()), for converting such an object to an RGBA tuple (to_rgba()) or to an HTML-like hex string in the#rrggbb format (to_hex()), and a sequence of colors to an (n, 4) RGBA array (to_rgba_array()). Caching is used for efficiency.

Commands which take color arguments can use several formats to specify the colors. For the basic built-in colors, you can use a single letter

  • b: blue
  • g: green
  • r: red
  • c: cyan
  • m: magenta
  • y: yellow
  • k: black
  • w: white

To use the colors that are part of the active color cycle in the current style, use C followed by a digit. For example:

  • C0: The first color in the cycle
  • C1: The second color in the cycle

Gray shades can be given as a string encoding a float in the 0-1 range, e.g.:

color = '0.75'

For a greater range of colors, you have two options. You can specify the color using an html hex string, as in:

color = '#eeefff'

(possibly specifying an alpha value as well), or you can pass an (r, g, b) or (r, g, b, a) tuple, where each of rgb and a are in the range [0,1].

Finally, legal html names for colors, like ‘red’, ‘burlywood’ and ‘chartreuse’ are supported.class matplotlib.colors.BoundaryNorm(boundariesncolorsclip=False)

Bases: matplotlib.colors.Normalize

Generate a colormap index based on discrete intervals.

Unlike Normalize or LogNormBoundaryNorm maps values to integers instead of to the interval 0-1.

Mapping to the 0-1 interval could have been done via piece-wise linear interpolation, but using integers seems simpler, and reduces the number of conversions back and forth between integer and floating point.boundariesa monotonically increasing sequencencolorsnumber of colors in the colormap to be used

If:

b[i] <= v < b[i+1]

then v is mapped to color j; as i varies from 0 to len(boundaries)-2, j goes from 0 to ncolors-1.

Out-of-range values are mapped to -1 if low and ncolors if high; these are converted to valid indices byColormap.__call__() . If clip == True, out-of-range values are mapped to 0 if low and ncolors-1 if high.inverse(value)class matplotlib.colors.Colormap(nameN=256)

Bases: object

Baseclass for all scalar to RGBA mappings.

Typically Colormap instances are used to convert data values (floats) from the interval [0, 1] to the RGBA color that the respective Colormap represents. For scaling of data into the [0, 1] interval seematplotlib.colors.Normalize. It is worth noting that matplotlib.cm.ScalarMappable subclasses make heavy use of this data->normalize->map-to-color processing chain.

Parameters:name : strThe name of the colormap.N : intThe number of rgb quantization levels.

colorbar_extend = None

When this colormap exists on a scalar mappable and colorbar_extend is not False, colorbar creation will pick up colorbar_extend as the default value for the extend keyword in thematplotlib.colorbar.Colorbar constructor.is_gray()set_bad(color=’k’alpha=None)

Set color to be used for masked values.set_over(color=’k’alpha=None)

Set color to be used for high out-of-range values. Requires norm.clip = Falseset_under(color=’k’alpha=None)

Set color to be used for low out-of-range values. Requires norm.clip = Falseclass matplotlib.colors.LightSource(azdeg=315altdeg=45hsv_min_val=0hsv_max_val=1hsv_min_sat=1hsv_max_sat=0)

Bases: object

Create a light source coming from the specified azimuth and elevation. Angles are in degrees, with the azimuth measured clockwise from north and elevation up from the zero plane of the surface.

The shade() is used to produce “shaded” rgb values for a data array. shade_rgb() can be used to combine an rgb image with The shade_rgb() The hillshade() produces an illumination map of a surface.

Specify the azimuth (measured clockwise from south) and altitude (measured up from the plane of the surface) of the light source in degrees.

Parameters:azdeg : number, optionalThe azimuth (0-360, degrees clockwise from North) of the light source. Defaults to 315 degrees (from the northwest).altdeg : number, optionalThe altitude (0-90, degrees up from horizontal) of the light source. Defaults to 45 degrees from horizontal.

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
1bdBorder width in pixels. Default is 2.
2bgNormal background color.
3confineIf true (the default), the canvas cannot be scrolled outside of the scrollregion.
4cursorCursor used in the canvas like arrow, circle, dot etc.
5heightSize of the canvas in the Y dimension.
6highlightcolorColor shown in the focus highlight.
7reliefRelief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE.
8scrollregionA 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.
9widthSize of the canvas in the X dimension.
10xscrollincrementIf 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.
11xscrollcommandIf the canvas is scrollable, this attribute should be the .set() method of the horizontal scrollbar.
12yscrollincrementWorks like xscrollincrement, but governs vertical movement.
13yscrollcommandIf 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 −

TK Canvas

Widgets:

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
1ButtonThe Button widget is used to display buttons in your application.
2CanvasThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.
3CheckbuttonThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.
4EntryThe Entry widget is used to display a single-line text field for accepting values from a user.
5FrameThe Frame widget is used as a container widget to organize other widgets.
6LabelThe Label widget is used to provide a single-line caption for other widgets. It can also contain images.
7ListboxThe Listbox widget is used to provide a list of options to a user.
8MenubuttonThe Menubutton widget is used to display menus in your application.
9MenuThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.
10MessageThe Message widget is used to display multiline text fields for accepting values from a user.
11RadiobuttonThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.
12ScaleThe Scale widget is used to provide a slider widget.
13ScrollbarThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14TextThe Text widget is used to display text in multiple lines.
15ToplevelThe Toplevel widget is used to provide a separate window container.
16SpinboxThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.
17PanedWindowA PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically.
18LabelFrameA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.
19tkMessageBoxThis 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.

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.

Label

The Tkinter Label Widget

The Label widget is a standard Tkinter widget used to display a text or image on the screen. The label can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut.

When to use the Label Widget

Labels are used to display texts and images. The label widget uses double buffering, so you can update the contents at any time, without annoying flicker.

To display data that the user can manipulate in place, it’s probably easier to use the Canvas widget.

Patterns #

To use a label, you just have to specify what to display in it (this can be text, a bitmap, or an image):

from Tkinter import *

master = Tk()

w = Label(master, text="Hello, world!")
w.pack()

mainloop()

If you don’t specify a size, the label is made just large enough to hold its contents. You can also use the height and width options to explicitly set the size. If you display text in the label, these options define the size of the label in text units. If you display bitmaps or images instead, they define the size in pixels (or other screen units). See the Button description for an example how to specify the size in pixels also for text labels.

You can specify which color to use for the label with the foreground (or fg) and background (or bg) options. You can also choose which font to use in the label (the following example uses Tk 8.0 font descriptors). Use colors and fonts sparingly; unless you have a good reason to do otherwise, you should stick to the default values.

w = Label(master, text="Rouge", fg="red")
w = Label(master, text="Helvetica", font=("Helvetica", 16))

Labels can display multiple lines of text. You can use newlines or use the wraplength option to make the label wrap text by itself. When wrapping text, you might wish to use the anchor and justify options to make things look exactly as you wish. An example:

w = Label(master, text=longtext, anchor=W, justify=LEFT)

You can associate a Tkinter variable with a label. When the contents of the variable changes, the label is automatically updated:

v = StringVar()
Label(master, textvariable=v).pack()

v.set("New Text!")

You can use the label to display PhotoImage and BitmapImage objects. When doing this, make sure you keep a reference to the image object, to prevent it from being garbage collected by Python’s memory allocator. You can use a global variable or an instance attribute, or easier, just add an attribute to the widget instance:

photo = PhotoImage(file="icon.gif")
w = Label(parent, image=photo)
w.photo = photo
w.pack()

Button

The Tkinter Button Widget

The Button widget is a standard Tkinter widget used to implement various kinds of buttons. Buttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.

The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget.

When to use the Button Widget #

Simply put, button widgets are used to let the user say “do this now!,” where thisis either given by the text on the button, or implied by the icon displayed in the button. Buttons are typically used in toolbars, in application windows, and to accept or dismiss data entered into a dialog box.

For buttons suitable for data entry, see the Checkbutton and Radiobuttonwidgets.

Patterns #

Plain buttons are pretty straightforward to use. All you have to do is to specify the button contents (text, bitmap, or image) and what function or method to call when the button is pressed:

from Tkinter import *

master = Tk()

def callback():
    print "click!"

b = Button(master, text="OK", command=callback)
b.pack()

mainloop()

A button without a callback is pretty useless; it simply doesn’t do anything when you press the button. You might wish to use such buttons anyway when developing an application. In that case, it is probably a good idea to disable the button to avoid confusing your beta testers:

b = Button(master, text="Help", state=DISABLED)

If you don’t specify a size, the button is made just large enough to hold its contents. You can use the padx and pady option to add some extra space between the contents and the button border.

You can also use the height and width options to explicitly set the size. If you display text in the button, these options define the size of the button in text units. If you display bitmaps or images instead, they define the size in pixels (or other screen units). You can specify the size in pixels even for text buttons, but that requires some magic. Here’s one way to do it (there are others):

f = Frame(master, height=32, width=32)
f.pack_propagate(0) # don't shrink
f.pack()

b = Button(f, text="Sure!")
b.pack(fill=BOTH, expand=1)

Buttons can display multiple lines of text (but only in one font). You can use newlines, or use the wraplength option to make the button wrap text by itself. When wrapping text, use the anchorjustify, and possibly padx options to make things look exactly as you wish. An example:

b = Button(master, text=longtext, anchor=W, justify=LEFT, padx=2)

To make an ordinary button look like it’s held down, for example if you wish to implement a toolbox of some kind, you can simply change the relief from RAISED to SUNKEN:

b.config(relief=SUNKEN)

You might wish to change the background as well. Note that a possibly better solution is to use a Checkbutton or Radiobutton with the indicatoronoption set to false:

b = Checkbutton(master, image=bold, variable=var, indicatoron=0)

In earlier versions of Tkinter, the image option overrides the text option. If you specify both, only the image is displayed. In later versions, you can use thecompound option to change this behavior. To display text on top of an image, set compound to CENTER:

b = Button(master, text="Click me", image=pattern, compound=CENTER)

To display an icon along with the text, set the option to one of LEFTRIGHTTOP, or BOTTOM:

# put the icon to the left of the text label
b = Button(compound=LEFT, image=icon, text="Action")

# put the icon on top of the text
b = Button(compound=TOP, image=icon, text="Quit")

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
1activebackgroundBackground color when the checkbutton is under the cursor.
2activeforegroundForeground color when the checkbutton is under the cursor.
3bgThe normal background color displayed behind the label and indicator.
4bitmapTo display a monochrome image on a button.
5bdThe size of the border around the indicator. Default is 2 pixels.
6commandA procedure to be called every time the user changes the state of this checkbutton.
7cursorIf 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.
8disabledforegroundThe foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color.
9fontThe font used for the text.
10fgThe color used to render the text.
11heightThe number of lines of text on the checkbutton. Default is 1.
12highlightcolorThe color of the focus highlight when the checkbutton has the focus.
13imageTo display a graphic image on the button.
14justifyIf the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
15offvalueNormally, 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.
16onvalueNormally, 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.
17padxHow much space to leave to the left and right of the checkbutton and text. Default is 1 pixel.
18padyHow much space to leave above and below the checkbutton and text. Default is 1 pixel.
19reliefWith 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
20selectcolorThe color of the checkbutton when it is set. Default is selectcolor=”red”.
21selectimageIf you set this option to an image, that image will appear in the checkbutton when it is set.
22stateThe 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.
23textThe label displayed next to the checkbutton. Use newlines (“\n”) to display multiple lines of text.
24underlineWith 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.
25variableThe 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.
26widthThe 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.
27wraplengthNormally, 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
1deselect()Clears (turns off) the checkbutton.
2flash()Flashes the checkbutton a few times between its active and normal colors, but leaves it the way it started.
3invoke()You can call this method to get the same actions that would occur if the user clicked on the checkbutton to change its state.
4select()Sets (turns on) the checkbutton.
5toggle()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 −

TK Checkbox

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
1bgThe normal background color displayed behind the label and indicator.
2bdThe size of the border around the indicator. Default is 2 pixels.
3commandA procedure to be called every time the user changes the state of this checkbutton.
4cursorIf 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.
5fontThe font used for the text.
6exportselectionBy default, if you select text within an Entry widget, it is automatically exported to the clipboard. To avoid this exportation, use exportselection=0.
7fgThe color used to render the text.
8highlightcolorThe color of the focus highlight when the checkbutton has the focus.
9justifyIf the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
10reliefWith 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
11selectbackgroundThe background color to use displaying selected text.
12selectborderwidthThe width of the border to use around selected text. The default is one pixel.
13selectforegroundThe foreground (text) color of selected text.
14showNormally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show=”*”.
15stateThe 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.
16textvariableIn 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.
17widthThe 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.
18xscrollcommandIf 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
1delete ( 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.
2get()Returns the entry’s current text as a string.
3icursor ( index )Set the insertion cursor just before the character at the given index.
4index ( 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.
5insert ( index, s )Inserts string s before the character at the given index.
6select_adjust ( index )This method is used to make sure that the selection includes the character at the specified index.
7select_clear()Clears the selection. If there isn’t currently a selection, has no effect.
8select_from ( index )Sets the ANCHOR index position to the character selected by index, and selects that character.
9select_present()If there is a selection, returns true, else returns false.
10select_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.
11select_to ( index )Selects all the text from the ANCHOR position up to but not including the character at the given index.
12xview ( index )This method is useful in linking the Entry widget to a horizontal scrollbar.
13xview_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

Try the following example yourself −

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 −

TK Entry

Python Tkinter 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.

  1. w = Listbox(parent, options)   

A list of possible options is given below.

SNOptionDescription
1bgThe background color of the widget.
2bdIt represents the size of the border. Default value is 2 pixel.
3cursorThe mouse pointer will look like the cursor type like dot, arrow, etc.
4fontThe font type of the Listbox items.
5fgThe color of the text.
6heightIt represents the count of the lines shown in the Listbox. The default value is 10.
7highlightcolorThe color of the Listbox items when the widget is under focus.
8highlightthicknessThe thickness of the highlight.
9reliefThe type of the border. The default is SUNKEN.
10selectbackgroundThe background color that is used to display the selected text.
11selectmodeIt is used to determine the number of items that can be selected from the list. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.
12widthIt represents the width of the widget in characters.
13xscrollcommandIt is used to let the user scroll the Listbox horizontally.
14yscrollcommandIt is used to let the user scroll the Listbox vertically.

Methods

There are the following methods associated with the Listbox.

SNMethodDescription
1activate(index)It is used to select the lines at the specified index.
2curselection()It returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple.
3delete(first, last = None)It is used to delete the lines which exist in the given range.
4get(first, last = None)It is used to get the list items that exist in the given range.
5index(i)It is used to place the line with the specified index at the top of the widget.
6insert(index, *elements)It is used to insert the new lines with the specified number of elements before the specified index.
7nearest(y)It returns the index of the nearest line to the y coordinate of the Listbox widget.
8see(index)It is used to adjust the position of the listbox to make the lines specified by the index visible.
9size()It returns the number of lines that are present in the Listbox widget.
10xview()This is used to make the widget horizontally scrollable.
11xview_moveto(fraction)It is used to make the listbox horizontally scrollable by the fraction of width of the longest line present in the listbox.
12xview_scroll(number, what)It is used to make the listbox horizontally scrollable by the number of characters specified.
13yview()It allows the Listbox to be vertically scrollable.
14yview_moveto(fraction)It is used to make the listbox vertically scrollable by the fraction of width of the longest line present in the listbox.
15yview_scroll (number, what)It is used to make the listbox vertically scrollable by the number of characters specified.

Example 1

  1. # !/usr/bin/python3  
  2.   
  3. from tkinter import *  
  4.   
  5. top = Tk()  
  6.   
  7. top.geometry(“200×250”)  
  8.   
  9. lbl = Label(top,text = “A list of favourite countries…”)  
  10.   
  11. listbox = Listbox(top)  
  12.   
  13. listbox.insert(1,”India”)  
  14.   
  15. listbox.insert(2, “USA”)  
  16.   
  17. listbox.insert(3, “Japan”)  
  18.   
  19. listbox.insert(4, “Austrelia”)  
  20.   
  21. lbl.pack()  
  22. listbox.pack()  
  23.   
  24. top.mainloop()  

Python Tkinter Message

The Message widget is used to show the message to the user regarding the behaviour of the python application. The message widget shows the text messages to the user which can not be edited.

The message text contains more than one line. However, the message can only be shown in the single font.

The syntax to use the Message widget is given below.

Syntax

  1. w = Message(parent, options)  

A list of possible options is given below.

SNOptionDescription
1anchorIt is used to decide the exact position of the text within the space provided to the widget if the widget contains more space than the need of the text. The default is CENTER.
2bgThe background color of the widget.
3bitmapIt is used to display the graphics on the widget. It can be set to any graphical or image object.
4bdIt represents the size of the border in the pixel. The default size is 2 pixel.
5cursorThe mouse pointer is changed to the specified cursor type. The cursor type can be an arrow, dot, etc.
6fontThe font type of the widget text.
7fgThe font color of the widget text.
8heightThe vertical dimension of the message.
9imageWe can set this option to a static image to show that onto the widget.
10justifyThis option is used to specify the alignment of multiple line of code with respect to each other. The possible values can be LEFT (left alignment), CENTER (default), and RIGHT (right alignment).
11padxThe horizontal padding of the widget.
12padyThe vertical padding of the widget.
13reliefIt represents the type of the border. The default type is FLAT.
14textWe can set this option to the string so that the widget can represent the specified text.
15textvariableThis is used to control the text represented by the widget. The textvariable can be set to the text that is shown in the widget.
16underlineThe default value of this option is -1 that represents no underline. We can set this option to an existing number to specify that nth letter of the string will be underlined.
17widthIt specifies the horizontal dimension of the widget in the number of characters (not pixel).
18wraplengthWe can wrap the text to the number of lines by setting this option to the desired number so that each line contains only that number of characters.

Example

  1. from tkinter import *  
  2.   
  3. top = Tk()  
  4. top.geometry(“100×100”)  
  5. var = StringVar()  
  6. msg = Message( top, text = “Welcome to Javatpoint”)  
  7.   
  8. msg.pack()  
  9. top.mainloop()  

Output:

Python Tkinter Message

The Tkinter Radiobutton Widget

The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.

The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget.

Each group of Radiobutton widgets should be associated with single variable. Each button then represents a single value for that variable.

When to use the Radiobutton Widget

The radiobutton widget is used to implement one-of-many selections. It’s almost always used in groups, where all group members use the same variable.

Patterns #

The Radiobutton widget is very similar to the check button. To get a proper radio behavior, make sure to have all buttons in a group point to the same variable, and use the value option to specify what value each button represents:

from Tkinter import *

master = Tk()

v = IntVar()

Radiobutton(master, text="One", variable=v, value=1).pack(anchor=W)
Radiobutton(master, text="Two", variable=v, value=2).pack(anchor=W)

mainloop()

If you need to get notified when the value changes, attach a command callback to each button.

To create a large number of buttons, use a loop:

    MODES = [
        ("Monochrome", "1"),
        ("Grayscale", "L"),
        ("True color", "RGB"),
        ("Color separation", "CMYK"),
    ]

    v = StringVar()
    v.set("L") # initialize

    for text, mode in MODES:
        b = Radiobutton(master, text=text,
                        variable=v, value=mode)
        b.pack(anchor=W)

Figure: Standard radiobuttons

To turn the above example into a “button box” rather than a set of radio buttons, set the indicatoron option to 0. In this case, there’s no separate radio button indicator, and the selected button is drawn as SUNKEN instead of RAISED:

Figure: Using indicatoron=0

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
1bgThe default background color of the text widget.
2bdThe width of the border around the text widget. Default is 2 pixels.
3cursorThe cursor that will appear when the mouse is over the text widget.
4exportselectionNormally, 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.
5fontThe default font for text inserted into the widget.
6fgThe color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default.
7heightThe height of the widget in lines (not pixels!), measured according to the current font size.
8highlightbackgroundThe color of the focus highlight when the text widget does not have focus.
9highlightcolorThe color of the focus highlight when the text widget has the focus.
10highlightthicknessThe thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight.
11insertbackgroundThe color of the insertion cursor. Default is black.
12insertborderwidthSize of the 3-D border around the insertion cursor. Default is 0.
13insertofftimeThe number of milliseconds the insertion cursor is off during its blink cycle. Set this option to zero to suppress blinking. Default is 300.
14insertontimeThe number of milliseconds the insertion cursor is on during its blink cycle. Default is 600.
15insertwidthWidth of the insertion cursor (its height is determined by the tallest item in its line). Default is 2 pixels.
16padxThe size of the internal padding added to the left and right of the text area. Default is one pixel.
17padyThe size of the internal padding added above and below the text area. Default is one pixel.
18reliefThe 3-D appearance of the text widget. Default is relief=SUNKEN.
19selectbackgroundThe background color to use displaying selected text.
20selectborderwidthThe width of the border to use around selected text.
21spacing1This 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.
22spacing2This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0.
23spacing3This 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.
24stateNormally, 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.
25tabsThis option controls how tab characters position text.
26widthThe width of the widget in characters (not pixels!), measured according to the current font size.
27wrapThis 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.
28xscrollcommandTo make the text widget horizontally scrollable, set this option to the set() method of the horizontal scrollbar.
29yscrollcommandTo 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
1delete(startindex [,endindex])This method deletes a specific character or a range of text.
2get(startindex [,endindex])This method returns a specific character or a range of text.
3index(index)Returns the absolute value of an index based on the given index.
4insert(index [,string]…)This method inserts strings at the specified index location.
5see(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
1index(mark)Returns the line and column location of a specific mark.
2mark_gravity(mark [,gravity])Returns the gravity of the given mark. If the second argument is provided, the gravity is set for the given mark.
3mark_names()Returns all marks from the Text widget.
4mark_set(mark, index)Informs a new position to the given mark.
5mark_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
1tag_add(tagname, startindex[,endindex] …)This method tags either the position defined by startindex, or a range delimited by the positions startindex and endindex.
2tag_configYou 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).
3tag_delete(tagname)This method is used to delete and remove a given tag.
4tag_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 −

TK Text

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.

When to use the Spinbox Widget

The Spinbox widget can be used instead of an ordinary Entry, in cases where the user only has a limited number of ordered values to choose from.

Note that the spinbox widget is only available Python 2.3 and later, when linked against Tk 8.4 or later. Also note that several Tk spinbox methods appears to be missing from the Tkinter bindings in Python 2.3.

Patterns #

The spinbox behaves pretty much like an ordinary Entry widget. The main difference is that you can specify what values to allow, either as a range, or using a tuple.

from Tkinter import *

master = Tk()

w = Spinbox(master, from_=0, to=10)
w.pack()

mainloop()

You can specify a set of values instead of a range:

w = Spinbox(values=(1, 2, 4, 8))
w.pack()

Scrollbar

When to use the Scrollbar Widget

This widget is used to implement scrolled listboxes, canvases, and text fields.

Patterns #

The Scrollbar widget is almost always used in conjunction with a ListboxCanvas, or Text widget. Horizontal scrollbars can also be used with the Entrywidget.

To connect a vertical scrollbar to such a widget, you have to do two things:

  1. Set the widget’s yscrollcommand callbacks to the set method of the scrollbar.
  2. Set the scrollbar’s command to the yview method of the widget.
from Tkinter import *

master = Tk()

scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(master, yscrollcommand=scrollbar.set)
for i in range(1000):
    listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

mainloop()

When the widget view is modified, the widget notifies the scrollbar by calling the set method. And when the user manipulates the scrollbar, the widget’s yviewmethod is called with the appropriate arguments.

Adding a horizontal scrollbar is as simple. Just use the xscrollcommandoption instead, and the xview method.

Menu

The goal of this widget is to allow us to create all kinds of menus that can be used by our applications. The core functionality provides ways to create three menu types: pop-up, toplevel and pull-down.

It is also possible to use other extended widgets to implement new types of menus, such as the OptionMenu widget, which implements a special type that generates a pop-up list of items within a selection.

Syntax

Here is the simple syntax to create this widget −

w = Menu ( 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.Description
1activebackgroundThe background color that will appear on a choice when it is under the mouse.
2activeborderwidthSpecifies the width of a border drawn around a choice when it is under the mouse. Default is 1 pixel.
3activeforegroundThe foreground color that will appear on a choice when it is under the mouse.
4bgThe background color for choices not under the mouse.
5bdThe width of the border around all the choices. Default is 1.
6cursorThe cursor that appears when the mouse is over the choices, but only when the menu has been torn off.
7disabledforegroundThe color of the text for items whose state is DISABLED.
8fontThe default font for textual choices.
9fgThe foreground color used for choices not under the mouse.
10postcommandYou can set this option to a procedure, and that procedure will be called every time someone brings up this menu.
11reliefThe default 3-D effect for menus is relief=RAISED.
12imageTo display an image on this menubutton.
13selectcolorSpecifies the color displayed in checkbuttons and radiobuttons when they are selected.
14tearoffNormally, a menu can be torn off, the first position (position 0) in the list of choices is occupied by the tear-off element, and the additional choices are added starting at position 1. If you set tearoff=0, the menu will not have a tear-off feature, and choices will be added starting at position 0.
15titleNormally, the title of a tear-off menu window will be the same as the text of the menubutton or cascade that lead to this menu. If you want to change the title of that window, set the title option to that string.

Methods

These methods are available on Menu objects −

Sr.No.Option & Description
1add_command (options)Adds a menu item to the menu.
2add_radiobutton( options )Creates a radio button menu item.
3add_checkbutton( options )Creates a check button menu item.
4add_cascade(options)Creates a new hierarchical menu by associating a given menu to a parent menu
5add_separator()Adds a separator line to the menu.
6add( type, options )Adds a specific type of menu item to the menu.
7delete( startindex [, endindex ])Deletes the menu items ranging from startindex to endindex.
8entryconfig( index, options )Allows you to modify a menu item, which is identified by the index, and change its options.
9index(item)Returns the index number of the given menu item label.
10insert_separator ( index )Insert a new separator at the position specified by index.
11invoke ( index )Calls the command callback associated with the choice at position index. If a checkbutton, its state is toggled between set and cleared; if a radiobutton, that choice is set.
12type ( index )Returns the type of the choice specified by index: either “cascade”, “checkbutton”, “command”, “radiobutton”, “separator”, or “tearoff”.

Example

Try the following example yourself −

from Tkinter import *

def donothing():
   filewin = Toplevel(root)
   button = Button(filewin, text="Do nothing button")
   button.pack()
   
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)

menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)
root.mainloop()

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

TK Menu

Leave a Reply

Your email address will not be published. Required fields are marked *