ListBox Widget
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
Output:
Example 2: Let’s Delete the elements from the above created listbox
Python3
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 −
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".
# Creating Menubar
menubar = Menu(root)
# 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:
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:
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.
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:
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.
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: