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

(singke) #1

Click here to view code image


self.label1 = Label(self, text='This is a test label')

There’s not too much that you have to worry about with labels. The hardest part is positioning them
inside the frame area in the window.


Adding the Button Widget


Buttons provide a way for application users to trigger event handlers in an application, such as to let
it know when there’s data in a form that needs to be read. This is the basic format for creating a
Button widget:


Click here to view code image


self.button1 = Button(self, text='Submit', command=self.calculate)

You must assign the Button widget to a unique variable name within the Application class.
With the Button widget, you should make sure to point the command parameter to the associated
event handler method in the Application class. If you don’t specify the command parameter, the
button won’t do anything when it’s clicked. Also, you need to use the grid() method to position the
button where you want it in the window frame area.


Working with the Checkbutton Widget


The Checkbutton widget provides an on-or-off type of interface. If the Checkbutton widget is
checked, it returns a 1 value, and if the widget is not checked, it returns a 0 value. The
Checkbutton widget is most commonly used to make selections of one or more items from a list
(such as selecting the toppings on a pizza).


Working with the Checkbutton widget is a bit tricky. You can’t directly access the
Checkbutton widget to find out whether it has been selected. Instead, you need to create a special
variable that can hold a value that represents the check box status. This is called a control variable.


You create a control variable by using one of four special methods:


BooleanVar()—For Boolean 0 and 1 values
DoubleVar()—For floating-point values
IntVar()—For integer values
StringVar()—For text values

Because the Checkbutton widget returns a Boolean value, you should use the BooleanVar()
control variable method. You must define this control variable as an attribute of the class object so
that you can reference it in the event handler method. You most often do this in the init()
method, as shown here:


Click here to view code image


self.varCheck1 = BooleanVar()

Then to link the control variable to the Checkbutton widget, you use the variable parameter
when you define the Checkbutton widget:


Click here to view code image


self.check1 = Checkbutton(self, text='Option1', variable=self.varCheck1)
Free download pdf