0% found this document useful (0 votes)
56 views25 pages

Unit 3 - Fundamentals of Python Programming Bio

UNIT 3 - FUNDAMENTALS OF PYTHON PROGRAMMING BIO

Uploaded by

Lilian P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views25 pages

Unit 3 - Fundamentals of Python Programming Bio

UNIT 3 - FUNDAMENTALS OF PYTHON PROGRAMMING BIO

Uploaded by

Lilian P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

SATHYABAMA

INSTITUTE OF SCIENCE AND TECHNOLOGY

SCSA1102 – FUNDAMENTALS OF PYTHON PROGRAMMING

UNIT – III - GUI PROGRAMMING

1
PYTHON (SCSA1102)
SYLLABUS

2
Python - GUI Programming - Tkinter
Tkinter:-
 Python has a lot of GUI frameworks, but Tkinter is
the only framework that’s built into the Python
standard library. Tkinter has several strengths.
 It’s cross-platform, so the same code works on
Windows, macOS, and Linux.
 The foundational element of a Tkinter GUI is
the window.
 Windows are the containers in which all other GUI
elements live.
 These other GUI elements, such as text boxes,
labels, and buttons, are known as widgets.
 Widgets are contained inside of windows.

3
https://realpython.com/python-gui-tkinter/
Python - GUI Programming - Tkinter
Working With Widgets
:- Widgets are the bread and butter of the Python GUI framework Tkinter.
 They are the elements through which users interact with your program.
 Each widget in Tkinter is defined by a class. Here are some of the widgets available:

4
https://realpython.com/python-gui-tkinter/
Python - GUI Programming - Tkinter
Python 3 - Tkinter Button:-
 The Button widget is used to add buttons in a Python application. These buttons can
display text or images that convey the purpose of the buttons. You can attach a
function or a method to a button which is called automatically when you click the
button.

from tkinter import *

from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack():
msg = messagebox.showinfo( "Hello Python", "Hello World")

B = Button(top, text = "Hello", command = helloCallBack)


B.place(x = 50,y = 50)
top.mainloop()

5
https://www.tutorialspoint.com/python3/tk_button.htm
Python - GUI Programming - Tkinter
Python 3 - Tkinter Entry :-
The Entry widget is used to accept single-line text strings from a user.
 If you want to display multiple lines of text that can be edited, then you should use the Text widget.
 If you want to display one or more lines of text that cannot be modified by the user, then you should use
the Label widget.

from tkinter import *

top = Tk()
L1 = Label(top, text = "User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd = 5)
E1.pack(side = RIGHT)

top.mainloop()

6
https://www.tutorialspoint.com/python3/tk_entry.htm
Python - GUI Programming - Tkinter
Python 3 - Tkinter Entry +Label + Button Code:-
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("400x500")
def hello():
data=E1.get()
#messagebox.showinfo("Say Hello", "Hello "+ data)
L2.config(text="HELLO "+data)
E1.delete(0, "end")
L1 = Label(top, text = "User Name")
L1.place(x = 35,y = 50)
E1 = Entry(top, bd = 5)
E1.place(x = 120,y = 50)
B1 = Button(top, text = "EXTRACT", command = hello)
B1.place(x = 55,y = 100)
L2 = Label(top, text = "",font = ("Comic Sans MS",20,"bold"))
L2.place(x = 55,y = 130)

top.mainloop()

7
Python - GUI Programming - Tkinter
Python 3 - Tkinter Radio Button :-
This widget implements a multiple-choice button, which is a way to offer many possible selections to the user and lets user
choose only one of them.
In order to implement this functionality, each group of radiobuttons must be associated to the same variable and each one
of the buttons must symbolize a single value. You can use the Tab key to switch from one radionbutton to another.
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)

root = Tk()
var = IntVar()
R1 = Radiobutton(root, text = "Option 1", variable = var, value = 1,command = sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text = "Option 2", variable = var, value = 2,command = sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text = "Option 3", variable = var, value = 3,command = sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()

8
https://www.tutorialspoint.com/python3/tk_radiobutton.htm
Python - GUI Programming - Tkinter
Python 3 - Tkinter Listbox :-
The Listbox widget is used to display a list of items from which a user can select a number of items

from tkinter import *


Syntax
Here is the simple syntax to create this widget − ws = Tk()
ws.title('Python Guides')
ws.geometry('400x300')
w = Listbox ( master, option, ... ) ws.config(bg='#446644')

def showSelected():
show.config(text=lb.get(ANCHOR))

lb = Listbox(ws)
lb.pack()
lb.insert(0, 'red')
lb.insert(1, 'green')
lb.insert(2, 'yellow')
lb.insert(3, 'blue')

Button(ws, text='Show Selected', command=showSelected).pack(pady=20)


show = Label(ws)
show.pack()
9
https://www.tutorialspoint.com/python3/tk_radiobutton.htm
Python - GUI Programming - Tkinter
Python 3 - Image:-
Tkinter’s label widget can be used to display either images or text. To display an image requires the use
of Image and ImageTk imported from the Python Pillow (aka PIL) package.

from tkinter import *


The ImageTk module contains support to create from PIL import ImageTk ,Image
and modify Tkinter BitmapImage and PhotoImage
root = Tk()
objects from PIL images. root.title('Show Image')

img=ImageTk.PhotoImage(Image.open ("sathyabama.jpg"))
lab=Label(image=img)
lab.pack()

button=Button(root,text=‘Exit',command=root.destroy)
button.pack()
root.mainloop()

10
https://www.tutorialspoint.com/python3/tk_radiobutton.htm
Python - GUI Programming - Tkinter
Python 3 – QRCODE GENERATION:- from tkinter import *
from PIL import ImageTk ,Image
import qrcode
QR Code stands for "Quick Response Code", QR Code
root = Tk()
has the capability to store lots of data when we scan root.title('Start Button')
the QR Code it will display the information. def generateqrcode():
# Create QR Code Object
qr_code = qrcode.QRCode(
# import Module version=1,
import qrcode box_size=3
)
# Create QR Code Object # Adding data
qr_code = qrcode.QRCode( qr_code.add_data('Add Some data')
qr_code.make(fit=True)
version=1,
# change color
box_size=3 qr_img = qr_code.make_image(fill_color="black", back_color="white")
) # save image
# Adding data qr_img.save("qr_image.png")
qr_code.add_data(‘We are Bio Groups of sathyabama') def displayqrcode():
qr_code.make(fit=True) generateqrcode()
img=ImageTk.PhotoImage(Image.open ("qr_image.png"))
L1.configure(image=img)
# change color L1.photo = img
qr_img = qr_code.make_image(fill_color="black", back_color="white")
L1= Label(root, text = "")
# save image L1.pack()
qr_img.save("qr_image.png") button1=Button(root,text='Generate',command=displayqrcode)
button1.pack()
button=Button(root,text='exit',command=root.destroy)
button.pack()
root.mainloop() 11
https://www.tutorialspoint.com/python3/tk_radiobutton.htm
Python - GUI Programming - Tkinter
Python 3 - Tkinter Scale:-
The Scale widget provides a graphical slider object that
allows you to select values from a specific scale

from tkinter import *

def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)

root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor = CENTER)

button = Button(root, text = "Get Scale Value", command = sel)


button.pack(anchor = CENTER)

label = Label(root)
label.pack()

root.mainloop()

12
https://www.tutorialspoint.com/python3/tk_scale.htm
Python - GUI Programming - Tkinter
Python 3 - Tkinter Scrollbar:-
This widget provides a slide controller that is used to
implement vertical scrolled widgets, such as Listbox,
Text and Canvas. Note that you can also create
horizontal scrollbars on Entry widgets. from tkinter import *

root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )

mylist = Listbox(root, yscrollcommand = scrollbar.set )


for line in range(100):
mylist.insert(END, "This is line number " + str(line))

mylist.pack( side = LEFT, fill = BOTH )


scrollbar.config( command = mylist.yview )

mainloop()

13
https://www.tutorialspoint.com/python3/tk_scrollbar.htm
Python - GUI Programming - Tkinter
from tkinter import *

Python 3 - Tkinter Canvas:- from tkinter import messagebox


top = Tk()
C = Canvas(top, bg = "blue", height = 250, width = 300)
The Canvas is a rectangular area intended for drawing coord = 10, 50, 240, 210
arc = C.create_arc(coord, start = 0, extent = 150, fill = "red")
pictures or other complex layouts. You can place graphics, line = C.create_line(10,10,200,200,fill = 'white')
text, widgets or frames on a Canvas. C.pack()
top.mainloop()
import tkinter as tk
from tkinter import *
from tkinter import Canvas
import time
import random
i=0
app = tk.Tk()
app.geometry('400x300')
app.config(bg='#E5E8E8')
app.title("Canvas")
def displayqrcode():
global i
i=i+5
canvas.create_rectangle(0, 0, 400, 300, fill="#E5E8E8")
canvas.create_arc(coord, start = 0, extent = i, fill = "red")
time.sleep(.1)
coord = 10, 50, 240, 210
canvas = Canvas(app)
canvas.pack()
button1=Button(app,text='Generate QRcode',command=displayqrcode)
https://www.tutorialspoint.com/python3/tk_canvas.htm button1.pack()
app.mainloop()
14
https://www.hashbangcode.com/article/drawing-shapes-tkinter-canvas-element-python
Python - GUI Programming - Tkinter
Tkinter Layout :-
The GUI Application Layout is mainly controlled by
Geometric Managers of Tkinter.

Tkinter has three built-in layout managers: the pack, grid,


and place managers.
 The place geometry manager positions widgets using
absolute positioning.
 The pack geometry manager organizes widgets in
horizontal and vertical boxes.
 The grid geometry manager places widgets in a two
dimensional grid.

15
https://zetcode.com/tkinter/layout/
Python - GUI Programming - Tkinter
pack() Method:-
from tkinter import *

root = Tk()
This geometry manager organizes widgets in blocks before placing them in frame = Frame(root)
frame.pack()
the parent widget.
Packing Algorithm: bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
The steps of Packing algorithm are as follows:
 Firstly this algorithm will compute a rectangular area known as redbutton = Button(frame, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
a Parcel which is tall (or wide) enough to hold the widget and then
it will fill the remaining width (or height) in the window with blank greenbutton = Button(frame, text = "Brown", fg = "brown")
greenbutton.pack( side = LEFT )
space.
 It will center the widget until any different location is specified. bluebutton = Button(frame, text = "Blue", fg = "blue")
bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text = "Black", fg = "black")


blackbutton.pack( side = BOTTOM)

root.mainloop()

16
https://www.studytonight.com/tkinter/python-tkinter-geometry-manager https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
grid() Method:-
This geometry manager organizes widgets in a table-like
structure in the parent widget. from tkinter import *
root = Tk( )
b=0
for r in range(6):
for c in range(6):
b=b+1
Button(root, text = str(b), borderwidth = 1 ).grid(row = r,column = c)

root.mainloop()

17
https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
place() Method:- from tkinter import *

top = Tk()
This geometry manager organizes widgets by placing them L1 = Label(top, text = "Physics")
L1.place(x = 10,y = 10)
in a specific position in the parent widget. E1 = Entry(top, bd = 5)
E1.place(x = 60,y = 10)
L2 = Label(top,text = "Maths")
L2.place(x = 10,y = 50)
E2 = Entry(top,bd = 5)
E2.place(x = 60,y = 50)

L3 = Label(top,text = "Total")
L3.place(x = 10,y = 150)
E3 = Entry(top,bd = 5)
E3.place(x = 60,y = 150)

B = Button(top, text = "Add")


B.place(x = 100, y = 100)
top.geometry("250x250+10+10")
top.mainloop()

18
https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
Tkinter event binding:-
import tkinter as tk
Assigning a function to an event of a widget is called event from tkinter import ttk

binding. When the event occurs, the assigned function is


invoked automatically. def return_pressed(event):
print('Return key pressed.')
he following shows the general syntax ofthe bind() method:
root = tk.Tk()
widget.bind(event, handler, add=None)
btn = ttk.Button(root, text='Save')
btn.bind('<Return>',
When an event occurs in the widget, Tkinter will invoke return_pressed)

the handler automatically with the event detail.


If you want to register an additional handler, you can pass btn.focus()
btn.pack(expand=True)
the '+' to the add argument. It means that you can have
multiple event handlers that respond to the same event. root.mainloop()

19
https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
Tkinter event binding:-
import tkinter as tk
In this example, the following statement calls from tkinter import ttk

the bind() method on the button widget to bind


the Return key pressed event: def return_pressed(event):
print('Return key pressed.')

btn.bind('<Return>', return_pressed)
def log(event):
print(event)
The following example illustrates how to use
the bind() method to register multiple handlers for the root = tk.Tk()
same event:
btn = ttk.Button(root, text='Save')
btn.bind('<Return>',
In this statement, the third argument add='+' registered return_pressed)
btn.bind('<Return>', log, add='+')
additional handler, which is the log() function.
If you don’t specify the add='+' argument,
btn.focus()
the bind() method will replace the existing handler btn.pack(expand=True)
(return_pressed) by the new one (log).
root.mainloop()

20
https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
Tkinter event binding:-
# Import the Required libraries
from tkinter import *

# Create an instance of tkinter frame or window


win= Tk()

# Set the size of the window


win.geometry("700x350")

# Define a function to display the message


def display_text(e):
label.config(text="Code never lies, comments sometimes do",
font=('Helvetica 17 bold'))

# Create a label widget to add some text


label= Label(win, text= "")
label.pack(pady= 50)

# Bind the Mouse button event


win.bind('<KeyPress-Alt_L>',display_text)
win.mainloop()

21
https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
Tkinter event binding:- KP_9 81 65434 9 on the keypad
.keysym .keycode .keysym_num Key KP_Add 86 65451 + on the keypad
Alt_L 64 65513 The left-hand alt key KP_Begin 84 65437 The center key (same key as 5) on the
Alt_R 113 65514 The right-hand alt key
BackSpace 22 65288 backspace keypad
Cancel 110 65387 break KP_Decimal 91 65439 Decimal (.) on the keypad
Caps_Lock 66 65549 CapsLock
Control_L 37 65507 The left-hand control key KP_Delete 91 65439 delete on the keypad
Control_R 109 65508 The right-hand control key KP_Divide 112 65455 / on the keypad
Delete 107 65535 Delete
Down 104 65364 ↓ KP_Down88 65433 ↓ on the keypad
End 103 65367 end KP_End 87 65436 end on the keypad
Escape 9 65307 esc
Execute 111 65378 SysReq KP_Enter 108 65421 enter on the keypad
F1 67 65470 Function key F1 KP_Home79 65429 home on the keypad
F2 68 65471 Function key F2
Fi 66+i 65469+i Function key Fi Print 111 65377 PrintScrn
F12 96 65481 Function key F12 Prior 99 65365 PageUp
Home 97 65360 home
Insert 106 65379 insert Return 36 65293 Enter key
Left 100 65361 ← Right 102 65363 →
Linefeed 54 106 Linefeed (control-J)
KP_0 90 65438 0 on the keypad Scroll_Lock 78 65300 ScrollLock
KP_1 87 65436 1 on the keypad Shift_L 50 65505 The left-hand shift key
KP_2 88 65433 2 on the keypad
KP_3 89 65435 3 on the keypad Shift_R 62 65506 The right-hand shift key
KP_4 83 65430 4 on the keypad Tab 23 65289 The tab key
KP_5 84 65437 5 on the keypad
KP_6 85 65432 6 on the keypad
KP_7 79 65429 7 on the keypad 22
KP_8 80 65431 8 on the keypad https://www.tutorialspoint.com/python3/tk_pack.htm
Python - GUI Programming - Tkinter
Tkinter Mouse event :-
from tkinter import *

def doSomething(event):
print("Mouse coordinates: " + str(event.x)+","+str(event.y))

window = Tk()

#window.bind("<Button-1>",doSomething) #left mouse click


window.bind("<Button-2>",doSomething) #scroll wheel
#window.bind("<Button-3>",doSomething) #right mouse click
#window.bind("<ButtonRelease>",doSomething)#mousebutton release
window.bind("<Enter>",doSomething) #enter the window
window.bind("<Leave>",doSomething) #leave the window
#window.bind("<Motion>",doSomething) #Where the mouse moved
window.mainloop()

23
Python - GUI Programming - Tkinter
Tkinter Extract Image Data (RGB – Hexadecimel Triplet):-

from PIL import Image


im = Image.open(r"bmw.jpg")
red_image_rgb = im.convert("RGB")
rgb_pixel_value = red_image_rgb.getpixel((10,15))
print(rgb_pixel_value)
print('#{:02x}{:02x}
{:02x}'.format( rgb_pixel_value[0],rgb_pixel_value[1],rgb_pixel_value[2]))

'''https://python.omics.wiki/plot/colors/rgb2hex'''

24
Python - GUI Programming - Tkinter
Tkinter Turtle:-
 Turtle is a special feathers of Python. Using Turtle, we can easily draw in a drawing board.
 First we import the turtle module. Then create a window, next we create turtle object and using
turtle method we can draw in the drawing board.
import turtle

t = turtle.Turtle()
# Star
for i in range(5): import turtle
t.forward(150) a = turtle.Turtle() #instantiate a new turtle object called 'a'
t.right(144) a.hideturtle() #make the turtle invisible
t.penup() a.penup() #don't draw when turtle moves
t.goto(50, 50) a.goto(-200, -200) #move the turtle to a location
t.pendown() a.showturtle() #make the turtle visible
# Polygon a.pendown() #draw when the turtle moves
for i in range(6): a.goto(50, 50) #move the turtle to a new location
t.forward(150)
t.right(300)

25
https://www.tutorialspoint.com/turtle-programming-in-python

You might also like