DIP Lab 3
DIP Lab 3
Name: _________________________________
Enrollment #: _________________________________
Class: _________________________________
Objective
The aim of today’s lab is to introduce you to interactive I/O operations in Python and creating and
handling Graphical User Interfaces (GUIs). You will also reduce the intensity resolution of the
image by using the shift operator. By the end of this lab, you should be able to:
Submission Requirements
You are expected to complete the assigned tasks within the lab session and show them to
the lab engineer/instructor. Get the lab journal signed by your instructor and submit it by the
end of lab session.
Tkinter:
The Tkinter module that comes with Python is as close as Python comes to having an official
graphics user interface (GUI), but no documentation is installed.
Our First Tkinter Program (File: hello1.py)
from tkinter import * #Please note small case lettering for tkinter
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
To run the program, run the script as usual. The following window appears. To stop the
program, just close the window. We start by importing the tkinter module. It contains all
classes, functions and other things needed to work with the Tk toolkit. In most cases, you can
simply import everything from Tkinter into your module’s namespace:
from tkinter import *
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 Tk class is
instantiated without arguments. This creates a top level widget of Tk which usually is the main
window of an application.
root = Tk()
A Label widget can display either text or an icon or other image. In this case, we use the text
option to specify which text to display. Next, we call the pack method on this widget. This tells
it to size itself to fit the given text, and make itself visible. However, the window won’t appear
until we’ve entered the Tkinter event loop:
root.mainloop()
The program will stay in the event loop until we close the window. The event loop doesn’t only
handle events from the user (such as mouse clicks and key presses) or the windowing system
(such as redraw events and window configuration messages), it also handles operations queued
by Tkinter itself. Among these operations are geometry management (queued by the pack
method) and display updates. This also means that the application window will not appear
before you enter the main loop.
When you run this example, the following window appears. This sample application is written
as a class. The constructor (the __init__ method) is called with a parent widget (the master), to
which it adds a number of child widgets. The constructor starts by creating a Frame widget. A
frame is a simple container, and is in this case only used to hold the other two widgets.
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
The frame instance is stored in a local variable called frame. After creating the widget, we
immediately call the pack method to make the frame visible. We then create two Button
widgets, as children to the frame.
This time, we pass a number of options to the constructor, as keyword arguments. The first
button is labelled “QUIT”, and is made red (fg is short for foreground). The second is labelled
“Hello”. Both buttons also take a command option. This option specifies a function, or (as in this
case) a bound method, which will be called when the button is clicked. The button instances are
stored in instance attributes. They are both packed, but this time with the side=LEFT argument.
This means that they will be placed as far left as possible in the frame; the first button is placed
at the frame’s left edge, and the second is placed just to the right of the first one (at the left
edge of the remaining space in the frame, that is). By default, widgets are packed relative to
their parent (which is master for the frame widget, and the frame itself for the buttons). If the
side is not given, it defaults to TOP.
The “hello” button callback is given next. It simply prints a message to the console every time
the button is pressed:
def say_hi(self):
print "hi there, everyone!"
Finally, we provide some script level code that creates a Tk root widget, and one instance of the
App class using the root widget as its parent:
root = Tk()
app = App(root)
root.mainloop()
root.destroy()
The mainloop call enters the Tk event loop, in which the application will stay until the quit
method is called (just click the QUIT button), or the window is closed. The destroy call is only
required if you run this example under certain development environments; it explicitly destroys
the main window when the event loop is terminated. Some development environments won’t
terminate the Python process unless this is done. More information on callback functions and
how to associate them with a particular widget e.g. a button: To use a function object as a
callback, pass it directly to Tkinter.
For each function object, the Tkinter interface layer registers a Tk command with a unique
name. When that Tk command is called by the Button implementation, the command calls
the corresponding Python function.
Tkinter’s Button widget doesn’t pass any information to the callback. This makes things a bit
complicated if you want to use the same callback for several buttons, like in this example:
def callback():
print ("button", "?")
Button(text="one", command=callback).pack()
Button(text="two", command=callback).pack()
Button(text="three", command=callback).pack()
A common beginner’s mistake is to call the callback function when constructing the
widget. That is, instead of giving just the function’s name (e.g. “callback”), the programmer
adds parentheses and argument values to the function:
def callback(number):
print ("button", number)
Button(text="one", command=callback(1)).pack()
Button(text="two", command=callback(2)).pack()
Button(text="three", command=callback(3)).pack()
If you do this, Python will call the callback function before creating the widget, and pass the
function’s return value to Tkinter. Tkinter then attempts to convert the return value to a string,
and tells Tk to call a function with that name when the button is activated. This is probably not
what you wanted. For simple cases like this, you can use a lambda expression as a link between
Tkinter and the callback function:
def callback(number):
print ("button", number)
Button(text="one", command=lambda: callback(1)).pack()
Button(text="two", command=lambda: callback(2)).pack()
Button(text="three", command=lambda: callback(3)).pack()
The Entry widget is a standard Tkinter widget used to enter or display a single line of text. To
create an Entry field you can use for typing/entering data:
The entry widget is used to enter text strings. This widget allows the user to enter one line
of text, in a single font. To enter multiple lines of text, use the Text widget.
Patterns
To add entry text to the widget, use the insert method. To replace the current text, you
can call delete before you insert the new text.
e = Entry(master)
e.pack()
e.delete(0, END)
e.insert(0, "a default value")
s = e.get()
You can also bind the entry widget to a StringVar instance, and set or get the entry text via
that variable:
v = StringVar()
e = Entry(master, textvariable=v)
e.pack()
v.set("a default value")
s = v.get()
This example creates an Entry widget, and a Button that prints the current contents:
Task 1: Load Image and Reset Image using tkinter and PIL
import tkinter as tk
import cv2
from PIL import ImageTk,Image
def onClick():
print("Button click")
img = ImageTk.PhotoImage(Image.open('C:/Users/Faculty/Desktop/dip la
b images/parrot.png'))
lb=tk.Label(image=img)
lb.place(x=130,y=50)
#lb.pack()
root.mainloop()
def onClick1():
print("Reset Button click")
img = ImageTk.PhotoImage(Image.open('C:/Users/Faculty/Desktop/dip la
b images/clear.PNG'))
lb=tk.Label(image=img)
lb.place(x=130,y=50)
#lb.pack()
root.mainloop()
root=tk.Tk()
root.title("First GUI")
root.geometry("500x350")
Output:
Exercise 1
def showImage():
fin=filedialog.askopenfilename(initialdir=os.getcwd(), title="Select
Image File",filetypes=(("PNG Files","*.png"),("JPG Files","*.jpg"),("AL
L Files","*.*")))
im=Image.open(fin)
im=ImageTk.PhotoImage(im)
lbl.configure(image=im)
lbl.image=im
root=tk.Tk()
frme=tk.Frame(root)
frme.pack(side=tk.BOTTOM, padx=15, pady=15)
lbl=tk.Label(root)
lbl.pack()
root.title("Browse Image")
root.geometry("350x350")
root.mainloop()
Output:
Exercise 2