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

(singke) #1
app = Application(root)
app.mainloop()

The code in the script1805.py file should look pretty familiar to you by now. It creates the
Application child class for the Frame object, defines the constructor, and defines the widgets to
place in the frame, including the two Checkbutton widgets. The button uses the display()
method for its event handler. The display() method retrieves the two control variable values used
for the Checkbutton widgets and displays a message in the command line, based on which
Checkbutton widget is selected.


Using the Entry Widget


The Entry widget is one of the most versatile widgets you’ll use in your applications. It creates a
single-line form field. A program user can use this field to enter text to submit to the program, or your
program can use it to display text dynamically in the window.


Creating an Entry widget isn’t very complicated:


self.entry1 = Entry(self)

The Entry widget doesn’t itself call an event handler. Normally, you link another widget, such as a
button, to an event handler that then retrieves the text that’s in the Entry widget or displays new text
in the Entry widget. To do that, you need to use the Entry widget’s get() method to retrieve the
text in the form field or the insert() method to display text in the form field.


Listing 18.6 shows the script1806.py program, which shows how to use the Entry widget both
for input and output for Python window scripts.


LISTING 18.6 The script1806.py Code


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):
self.label1 = Label(self, text='Please enter some text in lower
case')
self.label1.grid(row=0)
self.text1 = Entry(self)
self.text1.grid(row=2)

self.button1 = Button(self, text='Convert text',
command=self.convert)
self.button1.grid(row=6, column=0)
self.button2 = Button(self, text='Clear result',
command=self.clear)
Free download pdf