intro2cs tirgul 12 – networks and gui. today: network and communication gui - tkinter

Post on 06-Jan-2018

235 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Network  A computer network is a network which allows computers to exchange data  Networked computing devices exchange data with each other along data connections  The connections between computers are established using either cable media or wireless media.

TRANSCRIPT

INTRO2CSTirgul 12 – Networks and GUI

Today:

Network and Communication

GUI - tkinter

Network

A computer network is a network which allows computers to exchange data

Networked computing devices exchange data with each other along data connections

The connections between computers are established using either cable media or wireless media.

Client-Server Model

Client-Server Model

It is a network architecture in which each computer or process on the network is either a client or a server. 

The server component provides a function or service to one or many clients

 For instance, a web server serves web pages and a file server serves computer files. 

Client-Server Model

The client component request services from the server

For example, web browsers are clients that connect to web servers and retrieve web pages for display.

Server-Client Model Usage Examples

Email Printers Internet Atually, many of the application we use daily:

Whats up Facebook Waze Dropbox

Who can be a client? Server?

We are used to talk about servers (“ooh, Google servers are so strong!”) as a synonym for a powerful computer.

But, being a client or a server is just a role a specific program takes on itself.

We can run several program on the same machine :

Some would be clients that will reach other servers for service.

Some would be servers providing services to other clients, or even to a client on the current machine.

Client and Server Communication

Clients and servers exchange messages in a request–response messaging pattern: The client sends a request The server returns a response.

Client and Server Communication

To communicate, the computers must have a common language, and they must follow rules so that both the client and the server know what to expect.

The language and rules of communication are defined in a communications protocol

Address

(leaving a lot of details that will be revealed in a dedicated networks course) TCP-IP is one such communication protocol.

An IP defines the address of a computer in the form of 4, dot separated 8bit

numbers, e.g. : 127.0.0.1 The address can be defined by the name of

the machine, for example e-intro.cs.huji.ac.il When we want to use our computer as the

address we can use ‘localhost’TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

Ports

A port is the endpoint of the communication. It is always associated with the IP of a host

(for example, server) and the communication protocol

Specific port numbers are often used to identify specific services

Port 80 = HTTP, 443 = HTTPS Port 20 = FTP Port 6881 = Bittorent

TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

IP and Ports

We can say that the IP is the address is a building

If a letter is sent to this address without a specific apartment number, we cannot know which mailbox to put it in

So the IP is the building address and the port is the apartment number

IP, Ports and Sockets

The combination of an IP and a port defines a socket.

Sockets let us create a dedicated communication channel between two network entities. To\from this channel we can (similar to files syntax and terminology):

Write – to transfer information to the other side.

Read – to receive any information written to the channel by the other side.

TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

Networks with Python

The socket module lets us create and manage network communication via Python.

Creating a new socket object: import socketmy_socket = socket.socket()

Python’s socket object implement the general notion of network sockets and abstracts the “lower levels” of communication.

Networks with Python

For a full API see : https://docs.python.org/3/library/socket.html

For a nice tutorial : https://docs.python.org/3/howto/sockets.html#socket-howto

Client-server communication example

ClientServer

connecting a socket - client

Connecting a socket requires the definition of: Target address (host) : IP\host name. Target port : should be identical between both

sides. The connect method gets one parameter of the

address which is a tuple (IP, port)

connecting a socket - client

Lets see an example: what happens when we enter this url : https://docs.python.org in our browser:

address format is host and port number

Bind and listen: Server

Binding a socket = Declaring it is dedicated for a communication via a specific address.

listen : the dedicated communication channel (= the socket) will wait for client requests for connections.

If a connection is in progress and another request arrives, we put it in a queue. The queue size should be defined when we start to listen

Bind and listen: Server

We could have replaced socket.gethostname() with ‘localhost’, but then it would be visible only within the same machine

accept from a socket - server

Accepting communication could only be from a binded socket.

When the socket receives a request it returns: a new socket for sending and receiving

data. the address of the other side.

Type of Data

The type of data that is passed through the sockets is bytes.

We can encode any string we want as bytes. Any information read from the port should be

decoded from bytes to string. Encoding : The process of translating

characters to bytes\numbers. Famous encoding methods : UTF8, ASCII

bytes : when creating a bytes object from string we should declare what encoding to use (example coding = utf8) :

>> s = bytes('hi!','utf8') >> b‘hi!' # b stands for bytes >> s + 'bi'Traceback (most recent call last): File "<pyshell#66>", line 1, in <module> s + 'bi'TypeError: can't concat bytes to str

Encoding String Bytes

We decode using the same encoding method >> s = bytes('hi!',‘ascii') >> b'hi!' >> s.decode(‘ascii') >> 'hi!'

Dcoding Bytes String

Send Message

Send messages using the sendall method :my_socket.connect(address)my_socket.sendall(string_as_bytes)

Receive Message

Receive using the recv method.

Maximum amount of data to be received per single message is defined by BUFFER_SIZE.BUFFER_SIZE = 1024msg = my_socket.recv(BUFFER_SIZE)

Receive Message

We may receive more than one message.

How do we know when one message ends and the other begins?

We must define a protocol between the server and the client that both must obey.

Receive Message

For example, we can say that each message must end by a special character, like ‘\n’

So when we read ‘\n’ we know that this is the end of a message and all the data that comes after belongs to a new message

Receive Message

Receive Message

But what if we received only the beginning of a message after one call of recv?

We should get the rest of it in the next call, but we should keep the data we received in the previous call in a buffer

Receive Message

Receive Message

⬜When recv returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection

⬜But if the connection is not broken but there is no message to receive, we could wait forever…

Using Select

We can call select.select(rlist, wlist, xlist, timeout) to see if any of the input sockets are ready.

rlist: wait until ready for readingwlist: wait until ready for writingxlist: wait for an “exceptional condition” 

When the timeout argument is omitted the function blocks until at least socket is ready

https://docs.python.org/3/library/select.html

Using Select

The return value is a triple of lists of objects that are ready: subsets of the first three arguments.

When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.

https://docs.python.org/3/library/select.html

Using Select – Client example

s = socket.socket()s.connect((HOST, PORT))

# receiving data:while True: r,w,x = select.select([s], [], [], 5) for sock in r: if sock == s: data = r[0].recv(BUFF_SIZE) # do something with the data..

s.close()

reading from our socket

If there is no sockets to read we will not call recv and wait

closeing a socket

Same as files, when communication is terminated, the socket should be closed:my_socket.close()

GUI

Graphical User Interface

A GUI is a graphical (rather than purely textual) user interface to a computer

In the past interfaces to computers were not graphical, they were text-and-keyboard oriented

Today almost all operating systems, applications and programs we use consist of a GUI

GUI in Python

tkinter is the standard GUI library for Python

The GUI consist of the main window and different widgets within it

GUI in Python

To initialize Tkinter, we have to create a Tk root widget. This is an ordinary window, with a title bar and other decoration provided by your window manager.

You should only create one root widget for each program, and it must be created before any other widgets.

The root widget contains all other widgets

GUI in Python

After creating the main window and its contained widgets, the window will not appear until we will enter the event loop by calling mainloop() method on the main window

The program will stay in the event loop until we close the window.

It enables us to handle events from the user

GUI in Python

The window won’t appear until we’ve entered the Tkinter event loop (mainloop)

The program will stay in the event loop until we close the window. 

Widgets

 Widget is an element of interaction in a GUI, such as button or scroll bar

Tkinter provides the following widgets: Button Canvas entry Frame Label Menu text And many more.. http://www.python-course.eu/python_tkinter.php

Adding Widgets

All widgets are implemented in widgets classes, so each time we use a widget we create such object. 

The first parameter in the constructor of a widget is its parent widget

Widget Geometry Managers:

After adding a widget, we need to call a geometry manager in order to display it

There are three special methods that we can use for doing that: grid, pack and place

Try not to use grid and pack on the same container

Widget pack() Method

pack() method of the widget object: widget.pack(pack_options)

This organizes widgets in blocks before placing them in the parent widget.

The pack method doesn’t really display the widget; it adds the widget to a list of widgets managed by the parent widget

http://effbot.org/zone/tkinter-geometry.htm

Widget pack() options:expand: When set to true, widget expands to

fill any space not otherwise used in widget's parent.

fill: Determines whether widget fills any extra space allocated to it by the packer only horizontally, only vertically, both or none (defult)

side: Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.

Adding Widgets - Label

The label is a widget that the user just views but not interact with. 

A Label is a widget which is used to display text or an image.

We can set the text in the text argument in the Label constructor

More options: http://effbot.org/tkinterbook/label.htm

Adding Label Widget

Here we used text and font options

The Button Widget

Buttons can contain text or imagesButtons can be associated with a function or a

method that will be called after button click event

The association is by assigning command argument in the Button constructor to the function we wand to call

The Button Widget

Assigning the function that will be called on click event

The Button Widget

Clicking three times on the button:

The Canvas Widget

The Canvas widget provides structured graphics facilities 

It can be used to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.

To display things on the canvas, you create one or more canvas items using create methods

The create method returns the item id

Canvas Items and their Create Methods

◻arc◻image◻line◻oval◻polygon◻rectangle◻text◻window

◻create_arc◻create_image◻create_line◻create_oval◻create_polygon◻create_rectangl

e◻create_text◻create_window

Canvas items

The window coordinates of the canvas start at the upper left corner (this is (0,0))

The create methods get the coordinates as arguments, separated by commas

Canvas Widget

we set the color and the width of the line

Events and Bindings

When we run the mainloop(), we are actually in events loop

Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager

For each widget, we can bind Python functions and methods to events:

widget.bind(event, handler)

Events and Bindings

If an event matching the event description occurs in the widget, the given handler is called with an object describing the event.

The event is an object, and the handler is a callback method that we can implement.

Some Events Formats

<Button-1> , <Button-2>, <Button-3>A mouse button is pressed over the widget. Button 1 is the leftmost button, button 2 is the middle button (where available), and button 3 the rightmost button

The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.

Some Events Formats

<B1-Motion> The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button).

The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.

There are more events (mouse and keyboard):http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

Events and Bindings - example

Read about Frame widget: http://effbot.org/tkinterbook/frame.htm

The after Method

after(delay_ms, callback=None, *args)This is a widget method.It registers a callback function that will be called

after a given number of milliseconds. Since for running the GUI we are in a loop (the

mainloop()), we can use after to call a certain method over and over again

Using after example:

Protocols Handlers

The protocols refer to  interaction between the application and the window manager.

One example is closing a window using the window manager (the built-in x button on the upper right)

Say we want to do something when the user closes the window

We can use the protocol WM_DELETE_WINDOW

Protocols Handlers

The protocol method, much like bind, receives the protocol name and the handler (the method) that should be called upon it

Protocols HandlersLets close the window

We want to call this method upon closing the window

top related