The Listbox widget is used to display a list of items from which a user can select a number of items.
Syntax:
w = Listbox ( master, option, ... )
Example:
from Tkinter import *
master = Tk()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
mainloop()
Here:
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
There are many options which is given below:
bg
bd
cursor
Font
fg
height
releif
selectmode
width
selectbackground
Tkinter Menu
The Menu widget is used to implement toplevel, pulldown, and popup menus.
Syntax:
w = Menu ( master, option, ... )
Example:
import tkinter as tk
root = Tk()
def hello():
print "hello!"# create a toplevel menu
menubar = Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=root.quit)
# display the menu
root.config(menu=menubar)
Here:
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget.
Now we have creating Pulldown menus:
Example:
root = Tk()
def hello():
print "hello!"
menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=hello)
filemenu.add_command(label="Save", command=hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
# create more pulldown menus
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Cut", command=hello)
editmenu.add_command(label="Copy", command=hello)
editmenu.add_command(label="Paste", command=hello)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", command=hello)
menubar.add_cascade(label="Help", menu=helpmenu)
# display the menu
root.config(menu=menubar)
Now we have creating popup menu:
Example:
root = Tk()
def hello():
print "hello!"# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Undo", command=hello)
menu.add_command(label="Redo", command=hello)
# create a canvas
frame = Frame(root, width=512, height=512)
frame.pack()
def popup(event):
menu.post(event.x_root, event.y_root)
# attach popup to canvas
frame.bind("<Button-3>", popup)