Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


menubar = Menu(self)
filemenu = Menu(menubar)
filemenu.add_command(label='Convert', command=self.convert)
filemenu.add_command(label='Clear', command=self.clear)
menubar.add_cascade(label='File', menu=filemenu)
menubar.add_command(label='Quit', command=root.quit)
root.config(menu=menubar)

After you create the drop-down menu, you use the add_cascade() method to add it to the top-
level menu bar and assign it a label.


Now that you’ve learned about the popular widgets that you’ll use in your programs, you can work
out a real program to test them out!


Try It Yourself: Create a Python GUI Program
In the following steps, you’ll create a GUI application that can calculate your bowling
average after three games. Just follow these steps to get your program up and running:


  1. Create a file called script1809.py in the folder for this hour.

  2. Open the script1809.py file and enter the code shown here:
    Click here to view code image
    #!/usr/bin/python3
    from tkinter import *
    class Application(Frame):
    """Build the basic window frame template"""
    def init(self, master):
    super(Application, self).init(master)
    self.grid()
    self.create_widgets()
    def create_widgets(self):
    menubar = Menu(self)
    filemenu = Menu(menubar)
    filemenu.add_command(label='Calculate', command=self.calculate)
    filemenu.add_command(label='Reset', command=self.clear)
    menubar.add_cascade(label='File', menu=filemenu)
    menubar.add_command(label='Quit', command=root.quit)
    self.label1 = Label(self, text='The Bowling Calculator')
    self.label1.grid(row=0, columnspan=3)
    self.label2 = Label(self, text="Enter score from game 1:")
    self.label3 = Label(self, text='Enter score from game 2:')
    self.label4 = Label(self, text='Enter score from game 3:')
    self.label5 = Label(self, text="Average:")
    self.label2.grid(row=2, column=0)
    self.label3.grid(row=3, column=0)
    self.label4.grid(row=4, column=0)
    self.label5.grid(row=5, column=0)
    self.score1 = Entry(self)
    self.score2 = Entry(self)
    self.score3 = Entry(self)
    self.average = Entry(self)
    self.score1.grid(row=2, column=1)
    self.score2.grid(row=3, column=1)

Free download pdf