Easiest to Highest Python

[Pages:29]Easiest to Highest

Python

All rights reserved by John Yoon at Mercy College, New York, U.S.A. in 2017

PART 1: Python Element

1. Python Basics by Examples 2. Conditions and Repetitions 3. Data Manipulation

3.1 Acquiring Data 3.2 Handling Numbers 3.3 Handling Strings 4. Accessing External Sources 4.1 Accessing Files 4.2 Accessing Applications 4.3 Accessing Operating Systems 4.4 Accessing Database Servers 4.5 Accessing Networks 4.6 Accessing Webpages 5. Graphical User Interfaces 6. Python Advanced Programming 6.1 Command-line Parameters 6.2 Recursion 6.3 Multiprocessing 6.4 Multithreading

PART 2: Python Application

7. Financial Applications 8. Healthcare Applications 9. Cybersecurity Applications

a. Cyber Attack b. Cyber Defense 10. Wireless Communication and Security

10.1 Sinusoidal Wave and FFT 10.2 11. Data Mining and Machine Learning 12. xx 13.

APPENDIX

A. Setting Up Python Programming Environment

Chapter 5: Graphical User Interfaces

Note: Mac Users may want to download IDE "textwrangler" instead of "pyzo."

All the scripts considered so far are either dialog-based user interactive or non-user interactive. Dialogbased user interactive scripts guide users to respond to the prompted questions. An example of dialogbased user interactive scripts can be found in Python statements. There are primitive two Python statements for user interactions: input() and print(). For example,

name = input("Enter your name: ")

The function input() gives a query prompt "Enter your name:" to users and takes a user's typed string value, which is then assigned to the variable name. Hence, the variable name is in String type, and it holds the String value typed by a user. However, if you want to receive an integer, consider the following:

age = int(input("Enter your age: "))

The function input() receives user entered value, which should be checked or converted to an integer. For this outer function int() is used. If a user entered value is not an integer, it returns an error. If a float number is entered, it is converted into an integer.

Similarly, function print() displays data to the standard output, which is the monitor. A simple example is to say hello to users:

print("Hello")

There may be a special case that your Python script needs to display very lengthy text. Then, triple quotes can be used. See the example below:

print('''Hello, Mercy College! This is a sample user interface in Python statement. I am not sure if you like it... A lengthy text can be written and displayed if triple quotes are used like this.''')

One-step advanced user-interactive programs are to use graphic components. Examples of graphic components include buttons, textbox, labels, scroll bars, etc. The Python scripts that use graphic components for user interactions are called graphical user interfaces- (GUI-) based script.

This chapter describes various ways of GUI-based Python scripting.

5.1 Graphic Components

The GUI module package provided by Python is called tkinter. The module tkinter should be imported in scripts and the function Tk() instantiates a top level graphic component. Before discussing about graphic components available in tkinter, we will consider a simple GUI example.

EXAMPLE 5.1: Recall a script, My7loopTemp.py, converting Celsius temperature to Fahrenheit temperature in EXAMPLE 2.6. A similar computation can be displayed on GUI. Write a GUI script, gui1temp.py, which can convert a given number to both Celsius and Fahrenheit.

(a) Initial GUI

(b) Click the Upper Button

(c) Clicking the Lower Button also

The script code is as follows:

Script gui1temp.py

(1) from tkinter import *

(2) def convert2c():

(3) try:

(4)

f = float(tempIN.get())

(5)

c = (f -32)*5.0/9.0

(6)

tempOUTc.set(c)

(7) except ValueError:

(8)

pass

(9) def convert2f():

(10) try:

(11)

c = float(tempIN.get())

(12)

f = c*9.0/5.0 +32

(13)

tempOUTf.set(f)

(14) except ValueError:

(15)

pass

(16) root = Tk()

# the basic window, which is called here "root" is created.

(17) f=root

# to make the variable short, from "root" to "f"

(18) root.title("Temperature Converter")

(19) tempIN = StringVar() (20) tempOUTc = StringVar() (21) tempOUTf = StringVar()

(22) Label(f, text="Enter a temperature and click a button to convert...").grid(columnspan=4,row=0,sticky="w")

(23) Entry(f, textvariable=tempIN, width=7).grid(column=0, rowspan=2, row=1, sticky=W)

(24) Button(f, text="in F to Convert =>", command=convert2c).grid(column=1, row=1, sticky=W)

(25) Button(f, text="in C to Convert =>", command=convert2f).grid(column=1, row=2, sticky=W)

(26) Label(f, textvariable=tempOUTc).grid(column=2, row=1, sticky=(W, E)) (27) Label(f, textvariable=tempOUTf).grid(column=2, row=2, sticky=(W, E)) (28) Label(f, text="in C").grid(column=3, row=1, sticky=W) (29) Label(f, text="in F").grid(column=3, row=2, sticky=W)

(30) root.mainloop()

As shown above, the module tkinter should be imported in line (1) to render the graphic components, the classes Label, Entry, Button, etc. Those classes of graphic component are already defined and provided. Note that Label is a Python class and Label() is in an object constructor form, in which form, the class Label can be instantiated. What we can do in this example is to instantiate those classes. As a class is instantiated, some specific options can be defined by using arguments. For example, Button (root, fg="red", bg="blue"), where foreground and background colors can be specified.

The module tkinter has classes, Tk and Tcl. The class Tk() can be instantiated with no argument as shown in line (16). The two functions shown in lines (2)-(16) have been discussed in EXAMPLE 2.6. An object of Tk() is called the root of this GUI, which is the master or parent window. The graphic components of Label(), Entry() and Button() are contained in the master window, root. The object of Tk() first invokes the title() method to display the title of the GUI window in line (18). Renaming of a Tk() object in line(17) is redundant if the object reference root is used instead.

In order to refer the variables that are used in the logic of temperature conversions, the variables shown in graphic components are declared in lines (20)-(22). tempIN, tempOUTf, and tempOUTc are the variables holding the user input temperature, the conversion output to Fahrenheit, and the conversion output to Celsius, respectively. Those graphic components are then organized in grid layout, 4 columns and 3 rows.

On the first row, the text appears over those all four columns in left alignment by the statement sticky=W. Columns are spanned by columnspan=4 in line (23). The second and third rows have four columns, the input textbox, button to execute a conversion method, the output text, and the label to display the temperature unit, from left to right. User input can be received by the Entry() class in line (24). Here the variable tempIN is defined in this graphic component by textvariable=tempIN, which will be used in conversion processes as shown in lines (4) and (11).

Then, two buttons are created in lines (25) and (26). As a button is clicked, a corresponding method is executed as specified by command=convert2c and command=convert2f. In lines (27) and (28), the output tempOUTf or tempOUTc of those temperature conversion methods is displayed. The value held in such a variable is centralized in horizon alignment by sticky=(W,E). Finally, the units of temperature are shown in the Label() objects.

All of these graphic components are continued to run by root.mainloop(). Detailed description about tkinter can be found at .

EXERCISE 5.1: Write a Python script, grid1temp2.py, which has a few additions to the script, grid1temp.py in EXAMPLE 5.1. A sample run illustrates below:

The initial GUI shown above can be expanded as the conversion outcome is displayed.

Hint: Font and color can be defined as the class Entry and Label are instantiated. Note that the font can defined for font face (e.g., Helvetica), size (e.g., 24) and style (e.g., bald), and the color can be changed by adding fg="#xxxxxx" for foreground color setting, which is a RGB code in Hex.

Hint: Use the function .format() to define a decimal place. If you have a variable num holding 23.9876586, the following statement will format it to be 23.99:

`{:.2f}'.format(num)

In this way, the following GUI is possible.

5.2 Windows

The module tkinter provides a basic window by the constructor, Tk(). All graphical components can be placed on this basic window. There are three ways of placing graphical components: (1) The basic window can contain graphical components directly; (2) Canvas is placed on the basic window and it contains graphical components; and (3) similarly, Frame is placed on the basic window and a frame object contains graphical components. These are illustrated below:

(1) Graphical Components in Tk()

Output of 01createNone02.py

(2) Canvas in Tk(), where a canvas object contains graphical Output of 01createCanvas01.py components

(3) Frame in Tk(), where a frame object contains graphical Output of components

EXAMPLE 5.2: The Python file, back2gui01.py, defines a class to initialize a canvas. In the canvas, a rectangle and a square are drawn, where those two objects meet in the center of the canvas. Also a circle is drawn closer to the center. The source code is below:

Coding Source, back2gui01.py

from tkinter import *

def initialize(w,h): root = Tk() radius = h/10 root.title("New Mercy GUI-1") can = Canvas(root, bg="#1199fe", width=w,

height=h) can.create_rectangle(30, 20, w/2,h/2) can.create_rectangle(w/2-radius*3, h/2-

radius*3, w/2,h/2, fill="#FFFFFF") can.create_oval(w/2-radius,h/2-radius,

w/2+radius*5,h/2+radius*5, fill="#ff7711") can.pack() root.mainloop()

maxBound = input("Enter the width and height: ") splitVal = maxBound.split() width = int(splitVal[0]) height = int(splitVal[1]) print("w and h: {0} and {1}".format(width, height)) initialize(width, height)

Improved to Class

from tkinter import * class myPoly (object):

def __init__ (self, tit, w,h): #constructor

root = Tk() self.radius = h/10 root.title(tit+" of John Yoon") #self.can = Canvas(root, width=w, height=h) self.can = Canvas(root, bg="#1199fe", width=w, height=h) self.can.create_rectangle(30, 20, w/2,h/2) self.can.create_rectangle(w/2self.radius*3, h/2-self.radius*3, w/2,h/2, fill="#FFFFFF") self.can.create_oval(w/2self.radius,h/2-self.radius, w/2+self.radius*5.5,h/2+self.radius*5.5, fill="#ff7711") self.can.pack() root.mainloop()

def drawStar(self,w,h,k): pass

maxBound = input("Enter the width and height: ") splitVal = maxBound.split() width = int(splitVal[0]) height = int(splitVal[1])

obj = ["myObj", "yourObj", "herObj", "hisObjt"] for num, ob in enumerate(obj):

Sample myObj of John Yoon

yourObj of John Yoon herObj of John Yoon hisObj of John Yoon

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download