Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

ListBox widget

The ListBox widget is used to display different types of items. These items must be
of the same type of font and having the same font color. The items must also be of
Text type. The user can select one or more items from the given list according to the
requirement.
Syntax:
listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
Optional parameters
 root – root window.
 bg – background colour
 fg – foreground colour
 bd – border
 height – height of the widget.
 width – width of the widget.
 font – Font type of the text.
 highlightcolor – The colour of the list items when focused.
 yscrollcommand – for scrolling vertically.
 xscrollcommand – for scrolling horizontally.
 cursor – The cursor on the widget which can be an arrow, a dot etc.
Common methods
 yview – allows the widget to be vertically scrollable.
 xview – allows the widget to be horizontally scrollable.
 get() – to get the list items in a given range.
 activate(index) – to select the lines with a specified index.
 size() – return the number of lines present.
 delete(start, last) – delete lines in the specified range.
 nearest(y) – returns the index of the nearest line.
 curseselection() – returns a tuple for all the line numbers that are being
selected.
Example 1:
 Python3

from tkinter import *

# create a root window.


top = Tk()

# create listbox object


listbox = Listbox(top, height = 10,
width = 15,
bg = "grey",
activestyle = 'dotbox',
font = "Helvetica",
fg = "yellow")
# Define the size of the window.
top.geometry("300x250")

# Define a label for the list.


label = Label(top, text = " FOOD ITEMS")

# insert elements by their


# index and names.
listbox.insert(1, "Nachos")
listbox.insert(2, "Sandwich")
listbox.insert(3, "Burger")
listbox.insert(4, "Pizza")
listbox.insert(5, "Burrito")

# pack the widgets


label.pack()
listbox.pack()

# Display until User


# exits themselves.
top.mainloop()

Output:

Example 2: Let’s Delete the elements from the above created listbox
 Python3

# Delete Items from the list


# by specifying the index.
listbox.delete(2)

Output:

Menu button:
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.

1
activebackground
The background color that will appear on a choice when it is under the mouse.

2
activeborderwidth
Specifies the width of a border drawn around a choice when it is under the mouse.
Default is 1 pixel.

3
activeforeground
The foreground color that will appear on a choice when it is under the mouse.

4
bg
The background color for choices not under the mouse.

5
bd
The width of the border around all the choices. Default is 1.

6
cursor
The cursor that appears when the mouse is over the choices, but only when the menu
has been torn off.

7
disabledforeground
The color of the text for items whose state is DISABLED.

8
font
The default font for textual choices.

9
fg
The foreground color used for choices not under the mouse.

10
postcommand
You can set this option to a procedure, and that procedure will be called every time
someone brings up this menu.

11
relief
The default 3-D effect for menus is relief=RAISED.

12
image
To display an image on this menubutton.

13
selectcolor
Specifies the color displayed in checkbuttons and radiobuttons when they are
selected.

14
tearoff
Normally, 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.

15
title
Normally, 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

1
add_command (options)
Adds a menu item to the menu.

2
add_radiobutton( options )
Creates a radio button menu item.

3
add_checkbutton( options )
Creates a check button menu item.

4
add_cascade(options)
Creates a new hierarchical menu by associating a given menu to a parent menu

5
add_separator()
Adds a separator line to the menu.

6
add( type, options )
Adds a specific type of menu item to the menu.

7
delete( startindex [, endindex ])
Deletes the menu items ranging from startindex to endindex.

8
entryconfig( index, options )
Allows you to modify a menu item, which is identified by the index, and change
its options.

9
index(item)
Returns the index number of the given menu item label.

10
insert_separator ( index )
Insert a new separator at the position specified by index.

11
invoke ( 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.

12
type ( index )
Returns the type of the choice specified by index: either "cascade",
"checkbutton", "command", "radiobutton", "separator", or "tearoff".

importing only those functions


# which are needed
from tkinter import *
from tkinter.ttk import *
from time import strftime

# creating tkinter window


root = Tk()
root.title('Menu Demonstration')

# Creating Menubar
menubar = Menu(root)

# Adding File Menu and commands


file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)

# Adding Edit Menu and commands


edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)

# Adding Help Menu


help_ = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)

# display Menu
root.config(menu = menubar)
mainloop()
Output:

Dialogue box :
Tkinter (and TK of course) provides a set of dialogues (dialogs in American
English spelling), which can be used to display message boxes, showing
warning or errors, or widgets to select files and colours. There are also
simple dialogues, asking the user to enter string, integers or float numbers.
Let's look at a typical GUI Session with Dialogues and Message boxes.
There might be a button starting the dialogue, like the "quit" button in the
following window:

Pushing the "quit" button raises the Verify window:

Let's assume that we want to warn users that the "quit" functionality is not
yet implemented. In this case we can use the warning message to inform
the user, if he or she pushes the "yes" button:
If somebody types the "No" button, the "Cancel" message box is raised:

Let's go back to our first Dialogue with the "quit" and "answer" buttons. If
the "Answer" functionality is not implemented, it might be useful to use the
following error message box:

Python script, which implements the previous dialogue widges:

import tkinter as tk
from tkinter import messagebox as mb

def answer():
mb.showerror("Answer", "Sorry, no answer
available")

def callback():
if mb.askyesno('Verify', 'Really quit?'):
mb.showwarning('Yes', 'Not yet implemented')
else:
mb.showinfo('No', 'Quit has been cancelled')

tk.Button(text='Quit',
command=callback).pack(fill=tk.X)
tk.Button(text='Answer',
command=answer).pack(fill=tk.X)
tk.mainloop()

Message Boxes
The message dialogues are provided by the 'messagebox' submodule of
tkinter.

'messagebox' consists of the following functions, which correspond to


dialog windows:

 askokcancel(title=None, message=None, **options)


Ask if operation should proceed; return true if the answer is ok
 askquestion(title=None, message=None, **options)
Ask a question
 askretrycancel(title=None, message=None, **options)
Ask if operation should be retried; return true if the answer is yes
 askyesno(title=None, message=None, **options)
Ask a question; return true if the answer is yes
 askyesnocancel(title=None, message=None, **options)
Ask a question; return true if the answer is yes, None if cancelled.
 showerror(title=None, message=None, **options)
Show an error message
 showinfo(title=None, message=None, **options)
Show an info message
 showwarning(title=None, message=None, **options)
Show a warning message

Open File Dialogue


There is hardly any serious application, which doesn't need a way to read
from a file or write to a file. Furthermore, such an application might have to
choose a directory. Tkinter provides the module tkFileDialog for these
purposes.

import tkinter as tk
from tkinter import filedialog as fd

def callback():
name= fd.askopenfilename()
print(name)

errmsg = 'Error!'
tk.Button(text='File Open',
command=callback).pack(fill=tk.X)
tk.mainloop()

The code above creates a window with a single button with the text "File
Open". If the button is pushed, the following window appears:
The look-and-feel of the file-open-dialog depends on the GUI of the
operating system. The above example was created using a gnome desktop
under Linux. If we start the same program under Windows 7, it looks like
this:

Choosing a Colour
There are applications where the user should have the possibility to select
a colour. Tkinter provides a pop-up menu to choose a colour. To this
purpose we have to import the 'tkinter.colorchooser' module and have to
use the method askColor:

result = tkinter.colorchooser.askcolor ( color,


option=value, ...)
If the user clicks the OK button on the pop-up window, respectively, the
return value of askcolor() is a tuple with two elements, both a
representation of the chosen colour, e.g. ((106, 150, 98), '#6a9662')
The first element return[0] is a tuple (R, G, B) with the RGB representation
in decimal values (from 0 to 255). The second element return[1] is a
hexadecimal representation of the chosen colour.
If the user clicks "Cancel" the method returns the tuple (None, None).

The optional keyword parameters are:

color The variable color is used to set the default colour to be displayed.
If color is not set, the initial colour will be grey.
title The text assigned to the variable title will appear in the pop-up
window's title area. The default title is "Color".
parent Make the pop-up window appear over window W. The default
behaviour is that it appears over the root window.

Let's have a look at an example:

import tkinter as tk
from tkinter.colorchooser import askcolor

def callback():
result = askcolor(color="#6A9662",
title = "Bernd's Colour
Chooser")
print(result)

root = tk.Tk()
tk.Button(root,
text='Choose Color',
fg="darkgreen",
command=callback).pack(side=tk.LEFT,
padx=10)
tk.Button(text='Quit',
command=root.quit,
fg="red").pack(side=tk.LEFT, padx=10)
tk.mainloop()

The look and feel depends on the operating system (e.g. Linux or
Windows) and the chosen GUI (GNOME, KDE and so on). The following
windows appear, if you use Gnome:
Using the same script under Windows 7 gives us the following result:

You might also like