select website using python
Let’s Go Through This Again…
Event-Driven OOP…
Remember Visual Basic?...EVERYTHING In the User Interface Was an Object…
In GUI’s, the Terms “Objects” and “Events” Are Used Interchangeably…
Some Events Are “Fired” (i.e., When The User Does Something Like Click On A Button)…While Other Events Are “Triggered” (i.e., When a Function Calls Another Process Like During Error Processing)…
Applications Need To Monitor All Events And Respond To Them When They Occur…
A Function Which Performs An Action In Response To An Event Is Called An “Event Handler”…
We Bind “Handlers” To “Events”…
GUI Programs Are Event Driven Programs…
Event-Driven Programming…
Event Driven Programs Respond to Actions Regardless of the Order in Which They Occur…
In Event-Driven Programs You BIND (Associate) EVENTS (things that can happen) with EVENT HANDLERS (Code That Runs When the Events Occur)…
You Define Objects, Events, and Event Handlers…
You “Kick-Off” the Program by Entering an Event Loop..
The Program Waits for Events to Occur So It Can Handle Them…
Think of an ATM…
Common GUI Elements…
Frame: Holds Other GUI Elements…
Label: Displays Uneditable Text or Icons…
Button: Performs Some Action When the User Activates It…
Text Entry: Accepts and Displays One Line of Text…
Text Box: Accepts and Displays Multiple Lines of Text…
Check Button: Allows User to Select or Not Select ONE OR MORE Options…
Radio Button: Allows User to Select ONE Option From a Group of Options…
GUI Elements - the Basics…
These Elements Are Called “Widgets”...
Widget Classes Provide Default Functionality Which Simplifies Coding…
All Elements on Your Screen Must Sit in a Frame…
A Frame Can Be a Window or a Grouping Within a Window…
As We Create Layers of Screens and Menus, the Root Window is Said to Be a “Parent”…While the Subsequent Windows Are “Children”…
tkinter…
Is a Module in the Python Standard Library Which Serves as an Interface to “tk”…
Provides A Variety Of Common GUI Elements Which We Can Use To Build An Interface…
Other GUI Toolkits Are Available…But Are All Similar to “tkinter”…So Learning Them Should Be Easier…
NOTE: In Some Linux Systems (i.e., Ubuntu, Debian), “tkinter” Is Packaged Separately from the Rest of Python and Must Be Installed Separately…
Menus…
Tkinter Menus…
We Used Tkinter to Create Our Vending Machine…
But You Can Also Use Tkinter to Create Basic Menus…
The Core Functionality Provides Ways To Create Three Menu Types: Pop-Up, Top-Level And Pull-down…
It Is Also Possible To Use Other Extended Widgets To Implement New Types Of Menus, Such As The Optionmenu Widget, Which Implements A Special Type of Menu That Generates A Pop-up List Of Items Within A Selection…
Menu Widget…
Top Level Menus Are Displayed Just Under the Title Bar of the Root Menu…
Pull Down Menus Are Visible Textual Items on the Menu Bar…Often They Are Available Via Access Keys (i.e., <CTRL> + Key)…
Pop-Up Menus Are…Are…Pop-Up Menus…
Menu Syntax…
Syntax to Create a Menu Widget Is:
w = Menu (master, option, ...)
Parameters…
master : Represents the Parent Window…
options : Specific Types and Styles for the Menu…
Menu Methods – Part 1…
add_command (options) : Adds A Menu Item To The Menu…
add_radiobutton (options) : Creates A Radio Button Menu Item…
add_checkbutton (options) : Creates A Check Button Menu Item…
add_cascade (options) : Creates A New Hierarchical Menu By Associating A Given Menu To A Parent Menu…
add_separator () : Adds A Separator Line To The Menu…
add (type, options) : Adds A Specific Type Of Menu Item To The Menu…
delete (startindex [, endindex ]) : Deletes The Menu Items Ranging From Startindex To Endindex…
Menu Methods – Part 2…
entryconfig (index, options) : Allows you to modify a menu item, which is identified by the index, and change its options…
index (item) : Returns the index number of the given menu item label…
insert_separator (index) : Insert a new separator at the position specified by index….
invoke (index) : Calls the command callback associated with the choice at position index. If a checkbutton, its state is toggled between set and cleared; if a radiobutton, that choice is set…
type (index) : Returns the type of the choice specified by index: either "cascade", "checkbutton", "command", "radiobutton", "separator", or "tearoff“…
Menu Options – Part 1...
activebackground : Background Color That Will Appear On A Choice When It Is Under The Mouse…
activeborderwidth : Specifies The Width Of A Border Drawn Around A Choice When It Is Under The Mouse…Default Is 1 Pixel…
activeforeground : Foreground Color That Will Appear On A Choice When It Is Under The Mouse…
bg : Background Color For Choices Not Under The Mouse…
bd : Width Of The Border Around All The Choices…Default Is 1…
cursor : Cursor That Appears When The Mouse Is Over The Choices, But Only When The Menu Has Been Torn Off…
tearoff : Normally, A Menu Can Be Torn Off…The First Position (Position 0) In The List Of Choices Is Occupied By The Tear-off Element…And The Additional Choices Are Added Starting At Position 1…If You Set Tearoff = 0, The Menu Will Not Have A Tear-off Feature, And Choices Will Be Added Starting At Position 0…
Menu Options – Part 2…
disabledforeground : Color Of The Text For Items Whose State Is DISABLED…
font : Default Font For Textual Choices…
fg : Foreground Color Used For Choices Not Under The Mouse…
postcommand : Can Set This Option To A Procedure…That Procedure Will Be Called Every Time Someone Brings Up This Menu…
relief : Default 3-D Effect For Menus Is “relief = raised”…
image : Display An Image On The Menubutton…
selectcolor : Specifies The Color Displayed In Checkbuttons And Radiobuttons When They Are Selected…
title : Normally, The Title Of A Tear-off Menu Window Will Be The Same As The Text Of The Menubutton…If You Want To Change The Title Of That Window, Set The Title Option To That String…
Let’s Create a Simple Menu…
When the Code Below Is Executed, It Will Create the Following:
Let’s Code a Menu…
from tkinter import *
def close():
exit()
window = Tk()
menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label=“Close”, command=close)
menubar.add_cascade(label=“File”, menu=filemenu)
window.config(menu=menubar)
window.mainloop()
“Tkinter” Is Used in Python 2…Python 3 Uses “tkinter”…
Creates a Function called “close”…
The Function Will “exit” the Program…
Creates a Variable Called “window” that Uses the Tk Function…
“menubar” is the Menubar…and It Belongs to “window”…
“filemenu” Belongs to “menubar”…
Adds an Menu Item to the Pull Down Menu Item… When You Click It, It Will Execute the Function “close”
Adds a Pull Down Menu Item to the Menu Bar Called “File”…It Uses the Variable Menu (See Line 6)…
Uses Windows OS to Configure the Menu…
Runs a Continuous Loop Until You Press “Close”…
Let’s Create Another Menu…
When the Code Below Is Executed, It Will Create the Following:
Let’s Code Another Menu…
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label="New", command = donothing)
filemenu.add_command(label = "Open", command = donothing)
filemenu.add_command(label = "Save", command = donothing)
filemenu.add_command(label = "Save as...", command = donothing)
filemenu.add_command(label = "Close", command = donothing)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = root.quit)
menubar.add_cascade(label = "File", menu = filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label = "Undo", command = donothing)
editmenu.add_separator()
editmenu.add_command(label = "Cut", command = donothing)
editmenu.add_command(label = "Copy", command = donothing)
editmenu.add_command(label = "Paste", command = donothing)
editmenu.add_command(label = "Delete", command = donothing)
editmenu.add_command(label = "Select All", command = donothing)
menubar.add_cascade(label = "Edit", menu = editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label = "Help Index", command = donothing)
helpmenu.add_command(label = "About...", command = donothing)
menubar.add_cascade(label = "Help", menu = helpmenu)
root.config(menu = menubar)
root.mainloop()
Let’s Code a Menu…
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label="New", command = donothing)
filemenu.add_command(label = "Open", command = donothing)
filemenu.add_command(label = "Save", command = donothing)
filemenu.add_command(label = "Save as...", command = donothing)
filemenu.add_command(label = "Close", command = donothing)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = root.quit)
menubar.add_cascade(label = "File", menu = filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label = "Undo", command = donothing)
editmenu.add_separator()
editmenu.add_command(label = "Cut", command = donothing)
editmenu.add_command(label = "Copy", command = donothing)
editmenu.add_command(label = "Paste", command = donothing)
editmenu.add_command(label = "Delete", command = donothing)
editmenu.add_command(label = "Select All", command = donothing)
menubar.add_cascade(label = "Edit", menu = editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label = "Help Index", command = donothing)
helpmenu.add_command(label = "About...", command = donothing)
menubar.add_cascade(label = "Help", menu = helpmenu)
root.config(menu = menubar)
root.mainloop()
Hmmm, So What Does It Look Like?...
This Creates a Window With a Text Label and Two Buttons…
One Button Prints a Message…the Other Closes the Window…
The Window Has All the Properties of Any Window You Have Seen..
You Can Drag It Around, Resize It, And Maximize, Minimize Or Close It…
Create, Modify, Call a Root Window...
# Simple GUI to Create, Modify and Call a Root Window…
from tkinter import * # Imports ALL tikinter into code
# Create the Root Window
root = Tk() # Allows me to access any part of tkinter
#Modify the Window
root.title (‘Simple Gui’) # Sets the title in the root window
root.geometry (‘400x300’) # Sets the size of the root window in pixels
# Kick off the window’s event loop
root.mainloop() # Window stays open until someone closes it
What Does It Look Like?...
“Window Manager” Is Part Of Your OPERATING SYTEM!!!...It Handles Windows…
The Window Has All the Properties of Any Window You Have Seen..
You Can Drag It Around, Resize It, And Maximize, Minimize Or Close It…
Widgets Inside a Window (i.e., Buttons, Labels) May Look Different In Different GUI Toolkits…
However, the Way That the Window Frames and the Way Title Bars Look And Behave, Is Determined By Your “Window Manager” and Should Always Stay the Same…
Create a Frame and a Label…
# Labeler
# Demonstrates a label
from tkinter import *
# create the root window
root = Tk()
root.title("Labeler")
root.geometry("200x50")
# create a frame in the window to hold other widgets
app = Frame(root)
app.grid()
# create a label in the frame
lbl = Label(app, text = "I'm a label!")
lbl.grid()
# kick off the window's event loop
root.mainloop()
Buttons and More Buttons…
# Demonstrates creating buttons
from tkinter import *
# Create a root window
root = Tk()
root.title(“Lazy Buttons”)
root.geometry(“200x85”)
# Create a frame in the window to hold other widgets
app = Frame(root)
app.grid()
# Create a button in the frame
bttn1 = Button(app. Text = “I Do Nothing”)
bttn1.grid()
# Create a second button in the frame
bttn2 = Button(app)
bttn2.grid()
bttn2.configure(text = “Me Too!”)
# Create a third button in the frame
bttn3 = Button(app)
bttn3.grid()
Bttn3{“text”] = “Same Here!”
Movie Chooser…
class Application(Frame):
""" GUI Application for favorite movie type. """
def __init__(self, master):
""" Initialize Frame. """
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
""" Create widgets for movie type choices. """
# create description label
Label(self,
text = "Choose your favorite type of movie"
).grid(row = 0, column = 0, sticky = W)
# create instruction label
Label(self,
text = "Select one:"
).grid(row = 1, column = 0, sticky = W)
# create variable for single, favorite type of movie
self.favorite = StringVar()
self.favorite.set(None)
Movie Chooser…
# create Comedy radio button
Radiobutton(self,
text = "Comedy",
variable = self.favorite,
value = "comedy.",
command = self.update_text
).grid(row = 2, column = 0, sticky = W)
# create Drama radio button
Radiobutton(self,
text = "Drama",
variable = self.favorite,
value = "drama.",
command = self.update_text
).grid(row = 3, column = 0, sticky = W)
# create Romance radio button
Radiobutton(self,
text = "Romance",
variable = self.favorite,
value = "romance.",
command = self.update_text
).grid(row = 4, column = 0, sticky = W)
Movie Chooser…
# main
root = Tk()
root.title("Movie Chooser 2")
app = Application(root)
root.mainloop())
# create text field to display result
self.results_txt = Text(self, width = 40, height = 5, wrap = WORD)
self.results_txt.grid(row = 5, column = 0, columnspan = 3)
def update_text(self):
""" Update text area and display user's favorite movie type. """
message = "Your favorite type of movie is "
message += self.favorite.get()
self.results_txt.delete(0.0, END)
self.results_txt.insert(0.0, message)
Three Little Widgets and How They Grew…
All Three Widgets Can Display Text or Images…
“Tk” Is The Class Which We Use To Create The Root Window…It is the Parent…
“Button” and “Label” Should Be Self-Explanatory…They Are Children of Window…
Labels Are Static Elements…They Just Display Something…
Buttons Cause Something To Happen When They Are Clicked…
Applications Generally Have Only One Root…But It Is Possible To Create Other Windows Which Are Separate From The Main Window…
The Example Uses the “command” Keyword to Specify the Function Which Should Handle Each Button’s Click Events – Both Of These Functions Are Object Methods...
The Programs Uses the “Pack” Method On Each Widget To Position It Inside the Window…
Notice…
No Code Was Written to Make the Button’s Click Events Work…That Functionality Is Already Built Into The Button Objects…
We Did Not Have to Write a Function to Close the Window…There Is Already One Defined As A Method On The Window Object…
We DID Write Our Own Method For Printing A Message To The Console…
root.mainloop() Is A Method On The Main Window Which Runs the Application….
This Method Will Loop Forever Until the User Either Closes the Window Or Terminates the Program…
Widget Classes…
Frame: Container Widget Placed Inside A Window Which Can Have Its Own Border And Background…used To Group Related Widgets Together In An Application’s Layout…
Toplevel: Container Widget Displayed As A Separate Window…
Canvas: Widget Used for Drawing Graphics…In Advanced Usage, It Can Also Be Used To Create Custom Widgets…We Can Draw Anything Inside It And Make It Interactive…
Text: Displays Formatted Text Which Can Be Editable…Can Have Embedded Images…
Button: Usually Maps Directly To A User Action…i.e., When a User Clicks A Button, Something Should Happen…
Label: Displays Text Or An Image…Usually Isn’t Interactive…
Message: Similar To A Label, But Is Designed For Longer Bodies Of Text Which Need To Be Wrapped…
Scrollbar: Allows User To Scroll Through Content Which Is Too Large To Be Visible All At Once…
Checkbutton, Radiobutton, Listbox, Entry And Scale: Input Widgets…
Menu, Menubutton: Used To Create Pull-down Menus…
Layout Options…
There Are THREE Geometric Managers in tkinter…
Each Specifies a Position for Each Widget to Appear in a Window…
pack…
grid…
place…
“pack” Layout Method…
Arranges Widgets Vertically Inside Their Parent Container, From The Top Down
Can Change The Alignment To The Bottom, Left Or Right By Using The Optional Side Parameter…
Can Mix Different Alignments In The Same Container…This May Not Work Very Well For Complex Layouts…
from tkinter import LEFT, RIGHT
# (...)
self.label.pack()
self.greet_button.pack(side=LEFT)
self.close_button.pack(side=RIGHT)
“grid” Layout Method…
Recommended For Complex Interfaces…
Allows Us To Position Widgets In A More Flexible Way, Using A Grid Layout.
Each Widget Is Placed In A Cell Inside A Table By Specifying A Row And A Column…
The Default Row Is The First Available Empty Row, And The Default Column Is 0…
from tkinter
# (...)
self.greet_button.grid(row=1)
self.close_button.grid(row=1, Column=1)
“grid” Layout Method…Part 2…
Can Customize How Widgets Are Aligned Using the “sticky” Parameter…
Possible Values Are The Cardinal Directions (N, S, E And W)…
By Default, The Widget Is Centered Both Vertically And Horizontally…But We Can Make It “Stick” To A Particular Side By Including It In The Sticky Parameter…
sticky=w Will Cause The Widget To Be Left-aligned Horizontally…
sticky=w+e Will Cause It To Be Stretched To Fill The Whole Cell Horizontally...
Specify Corners Using NE, SW, Etc..
from tkinter import w
# (...)
self.label.grid(columnspan=2, sticky=w)
self.greet_button.grid(row=1)
self.close_button.grid(row=1, column=1)
Note on “pack” and “grid”…
Never Use Both “pack” And “grid” Inside The Same Window…
The Algorithms Used to Calculate Widget Positions Are Not Compatible With Each Other…
This May Cause Your Program to “Hang” Forever As tkinter Tries Unsuccessfully To Create A Widget Layout Which Satisfies Both “pack” and “grid”...
“place” Layout Method…
Allows Us To Provide Explicit Sizes And Positions For Widgets…
It Is Seldom A Good Idea To Use This Method For Ordinary GUIs – It Is Far Too Inflexible And Time Consuming To Specify An Absolute Position For Every Element…
There Are Some Specialized Cases In Which It Can Be Useful…
Custom Events…
Predefined Events Are Events That Are Defined in tkinter By Default…But We Are Not Restricted To These Particular Events
Custom Events Are Uniquely Identified By A Sequence Name In String Format…For Example:
"<Button-1>", "<Button-2>“, "<Button-3>“: Events Which Signal That A Particular Mouse Button Has Been Pressed While The Mouse Cursor Is Positioned Over The Widget In Question…Button 1 Is The Left Mouse Button…Button 3 Is The Right…Button 2 The Middle Button…
"<ButtonRelease-1>“: Indicates That The Left Button Has Been Released…
"<B1-motion>“: Indicates That The Mouse Was Moved While The Left Button Was Pressed…You Can Also Use B2 Or B3…
"<Enter>“, "<Leave>“: Mouse Cursor Has Entered Or Left The Widget…
"<Key>“: Any Key On The Keyboard Was Pressed…Can Also “Listen” For Specific Key Presses…For Example "<Return>“, or "<Shift-up>“…Key Presses Of Most Printable Characters Are Expressed As The Bare Characters, Without Brackets – For Example, The Letter A Is Just "A".
"<Configure>“: The Widget Has Changed Size…
So What Is This Code Doing?...
A SIMPLE Calculator…
Allow The User To Enter A Number In A Text Field, And Either Add It To Or Subtract It From A Running Total, Which We Will Display…we Will Also Allow The User To Reset The Total…
A SIMPLE Calculator…Part 1…
A SIMPLE Calculator…Part 2…
A SIMPLE Calculator – Explained…
There Are TWO Defined Methods In Our Class:
Validating Text Entry…
Update Total…
A SIMPLE Calculator – Validating Text Entry…
Checks That The Contents Of The Entry Field Are A Valid Integer…
The Value of the Contents Will ONLY Change, If the Value Entered is a Valid Number…
The Value Will Be Cleared If It Is Empty…
If the Value Of The Field Changes, We Store The Integer Value Of The Contents In “self.entered_number”…the Value Is Also Converted at This Point to an Integer…
This “validate” Function Must Return True If The Entry’s Value Is Allowed To Change And False Otherwise…
A SIMPLE Calculator – Update Total…
There Is A Single Handler For Updating The Total…
The Way We Update The Total Depends On the Button Pressed…
A Parameter Is Passed to the Handler…
First, Update Our Running Total Using The Integer Value Of The Entry Field Which Was Calculated And Stored Inside The Validate Method…
Then Update the Text Displayed By The Label With the New Total By Setting The New Value To The Label As Its Text Variable…
Clear the Value From The Entry Field Using The Entry Widget’s Delete Method…This Deletes All Characters From The First Index (Zero) To The End (End Is A Constant Defined By tkinter)…
Let’s Do a Project!…
Imitation Is The Sincerest Form Of Flattery…
46
Imitation Is The Sincerest Form Of Flattery...
And It Is So True Isn’t It?...
We Imitate All the Time, Don’t We…
In the Way We Dress…
The Way We Speak…
The Music We Listen To…
You Might Even Know Some People That Copy/Paste Work From the Internet and Submit It As Their Own As a Way of Flattery!...
So Let’s Do That For Your Final Project…
Imitation Is The Sincerest Form Of Flattery...
For This Assignment, You Need to Select a Website That You Will Recreate Using Python…
Websites Will Be Approved On a First Come First Served Basis…
Your Website Should “Imitate” the Look and Feel and Functionality of the Original…
Your Submitted Code Must Actually Work!...
For TONIGHT…I Need Your Website…
What Needs to Be Included in My Project?... How Does All This Work?!...
Here Are the Items You Need to Include…
String Methods (i.e., upper, lower, title, etc.)…
Nested If…
Loops…
Lists, Dictionary, Tuple…
Functions…
Passing Parameters…
Global, Local Parameters…
Files (new, write, append)…
Exception Handling…
Error Handling, Error Logs…
tkinter…
Widgets…
Grid, Layout…
Menus…
Classes…
Arrays (Single, Multi)…
User Reports, Error Log Report…
Do We Really Need ALL of That Stuff?!…
The Fact Is That to Build Any “Real” Application, You Would Need to Include Most If Not All of Those Items…
Just Design and Build…My Guess is that You Will Have All of Those Items With No Trouble…
Oh, and Little “Extras” In the System Are Always Impressive…As Long As They Work!...
Questions?...
Imitation Is The Sincerest Form Of Flattery...
By the Way…That Quote is From Oscar Wilde, an Author, Poet and Playwright…
The Entire Quote Is:
“Imitation is the sincerest form of flattery that mediocrity can pay to greatness.”
Questions?...
Good Luck!!!...