self.create_widgets()
def create_widgets(self):
self.label1 = Label(self, text='Select your items')
self.label1.grid(row=0)
self.listbox1 = Listbox(self, selectmode=EXTENDED)
items = ['Item One', 'Item Two', 'Item Three']
for item in items:
self.listbox1.insert(END, item)
self.listbox1.grid(row=1)
self.button1 = Button(self, text='Submit', command=self.display)
self.button1.grid(row=2)
def display(self):
"""Display the selected items"""
items = self.listbox1.curselection()
for item in items:
strItem = self.listbox1.get(item)
print(strItem)
print('----------')
root = Tk()
root.title('Listbox widget test')
root.geometry('300x200')
app = Application(root)
app.mainloop()
When you run the script1808.py code, anything you select from the list box will appear in the
command-line window when you click the Submit button.
Working with the Menu Widget
A staple of GUI programs is the menu bar at the top of the window. The menu bar provides drop-
down menus so that program users can quickly make selections. You can create menu bars in your
tkinter windows by using the Menu widget.
To create the main menu bar, you link the Menu widget directly to the Frame object. Then you use
the add_command() method to add individual menu entries. Each add_command() method
specifies a label parameter to define what text appears for the menu entry and a command
parameter to define the method to run when the menu entry is selected. Here’s how it looks:
Click here to view code image
menubar = Menu(self)
menubar.add_command(label='Help', command=self.help)
menubar.add_command(label='Exit', command=self.exit)
This creates a single menu bar at the top of the window, with two selections: Help and Exit. Finally,
you need to link the menu bar to the root Tk object by adding this command:
Click here to view code image
root.config(menu=self.menubar)
Now when you display your application, it will have a menu bar at the top, with the menu entries that
you defined.
You can create drop-down menus by creating additional Menu widgets and linking them to your main
menu bar Menu widget. That looks like this: