Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 81

GUI Using Python

Tkinter: 
is a Standard Python Library/GUI
• It is default GUI of python
• It comes with many functions and
methods that can be used to create
an application.
• #Import tkinter library
• from tkinter import *
• Import tkinter
Tkinter Programming
• Tkinter is the standard GUI library for Python.
• Python when combined with Tkinter provides
a fast and easy way to create GUI applications.
• Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
• Creating a GUI application using Tkinter is an
easy task.
•All you need to do is perform the following steps −
–Import the Tkinter module.
–Create the GUI application main window.
–Add one or more of the widgets to the GUI application.
–Enter the main event loop to take action against each event triggered by the
user.
Various GUI in Python
• Tkinter
• PyGUI
• PySimpleGUI
• Kivy
• PyForms
• Wax
Tk( )
• It manages all the other components of the
tkinter application.
• Use it to create instance of tkinter
• It helps to display the root window
• Tk is a interface inside the tkinter package
(“Tk interface”) is the standard Python
interface to the Tcl/Tk GUI toolkit.
Tkinter is Tk interface
• The Tk application object created by instantiating Tk.
• This provides access to the Tcl (Tool Command
Language) interpreter.
mainloop()
• As the name implies it will loop forever until the user
exits the window or waits for any events from the
user.
• mainloop() is simply a method in the main window
that executes what we wish to execute in an
application
Must use Tk() GUI toolkit
• Program1
Width=700
height=500
x=60
y=40
root.geometry(‘ 600x400 + 60 + 40 ')
Make fixed width height
• Use it as:
• window.resizable(width,height)

• root.geometry('600x400')
• root.resizable(False, False)
Tkinter Widgets
• Tkinter provides various controls, such as
buttons, labels and text boxes used in a GUI
application.
• These controls are commonly called widgets.
• There are currently 15 types of widgets in
Tkinter.
Standard attributes
• Let us take a look at how some of their
common attributes.
• Such as sizes, colors and fonts are specified.
– dimensions
– colors
– fonts
– anchors
– relief styles
– Bitmaps
Give a title
from tkinter import *

window=Tk() # add widgets here


window. title ('Hello Python')
window.geometry("300x50")
# x axis-300, y axis 50
window.mainloop()
geometry manager methods= 3
1. pack() method: It organizes the widgets in
blocks before placing in the parent widget.
2. grid() method: It organizes the widgets in
grid (table-like structure) before placing in
the parent widget.
3. place() method: It organizes the widgets by
placing them on specific positions directed by
the programmer.
Layout managers in Python: pack(),
place(), grid()
• pack() organizes widgets in
– horizontal boxes -> LEFT or RIGHT
– vertical boxes -> TOP or BOTTOM
– .pack(side = BOTTOM)
– Can use its more attributes
The pack() attributes
• We can give:
• padx =10, pady =20 ,
• side= LEFT/RIGHT/TOP/BOTTOM,
• fill= BOTH/ X / Y
– X, fill horizontally.
– Y, fill vertically.
– BOTH, fill horizontally and vertically.
• The expand= True or False
The pack() attributes
The place()
• place() places widgets in a two dimensional
grid using x and y absolute coordinates. 
The grid()
• e1.grid(row=0, column=1)
• e2.grid(row=1, column=1)
The grid()
• grid() locates widgets in a two dimensional grid
using row and column absolute coordinates. 
• Label(text=“Username", width=10). grid(row=0, column=1)
Create Label in tkinter with
Label ( )
About Label in tkinter
• The Label widget in Tkinter is used to display box
where you can place your images and text.
• The Label widget is mainly used to provide a
message about the other widgets used in the Python
Application to the user.
• You can change or update the text inside the label
widget anytime you want.
• This widget uses only one font at the time of
displaying some text.
Label attributes:
• bg : background colour
• fg : foreground colour
• font : font name and size
• padx:
• pady:
• justify:
• height:
• width:
• relief: appearance of border of label.
Button attributes:
• text : caption of the button
• bg : background colour
• fg : foreground colour
• font : font name and size
• image : to be displayed instead of text
• command : function to be called when clicked
Examples: Button, Label
Entry
from Tkinter import *
• program4
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)

top.mainloop()
Frame
from Tkinter import *
root = Tk()
• program5 frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")


greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")


bluebutton.pack( side = LEFT )

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


blackbutton.pack( side = BOTTOM)

root.mainloop()
#Create Label, Button and Textbox with Entry
# use of .place( ) to fix them ***
from tkinter import *
win = Tk()
win.geometry("400x250")
#creating a label
username = Label(win, text = "Username").place(x = 30,y = 50)
#creating second label
password = Label(win, text = "Password").place(x = 30, y = 90)
submitbutton = Button(win, text = "Submit",fg = "red", bg = "blue").place(x =
30, y = 120)

e1 = Entry(win,width = 20).place(x = 100, y = 50)


e2 = Entry(win, width = 20).place(x = 100, y = 90)
win.mainloop()
# add 3 frames and pack( ) each frame ***
#Frame in tkinter
from tkinter import *

win = Tk()
win.geometry("500x500+10+20")

frame1 = Frame(master=win, width=300, height=300, bg="pink")


frame1.pack()

frame2 = Frame(master=win, width=200, height=100, bg="grey")


frame2.pack()

frame3 = Frame(master=win, width=100, height=50, bg="green")


frame3.pack()

mainloop()
Button and apply tkMessageBox
on its command
The anchor
Canvas
• The Canvas is a rectangular area intended for
drawing pictures or other complex layouts.
We can place graphics, text, widgets or
frames on a Canvas.
• program3 import tkinter

top =tkinter.Tk()

C = tkinter.Canvas(top, bg="blue", height=250, width=300)

coord = 10, 50, 240, 210


arc = C.create_arc(coord, start=0, extent=15, fill="red")
C.pack()
top.mainloop()
Code for Canvas
• from tkinter import *
• top = Tk()
• C = tkinter.Canvas(top, bg="blue", height=900, width=300)

• coord = 10, 50, 240, 210


• arc = C.create_arc(coord, start=0, extent=90, fill="red")
• C.pack()

• mainloop()
For Student’s Practice
Further widgets are:
• Listbox
• Radiobutton
• Checkbutton
• Menubutton
• Spinbox
• Scale
• Message
• photoImage
The Listbox ( )
• It displays a list of text items.
• A Listbox allows to select one or multiple items at a time.
• Use the Listbox(container, height, list_variable)

• a listvariable should be a StringVar(value=items).


from Tkinter import *
Listbox import tkMessageBox
import Tkinter

• Program6 top = Tk()

Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")

Lb1.pack()
top.mainloop()
RadioButton
• Many buttons option, we can click on one
• Use tkinter variables (mainly
– IntVar and
– StringVar to access its state.
• Also called option button
• x = StringVar() # Holds a string; default value ""
• x = IntVar() # Holds an integer; default value 0
• x = DoubleVar() # Holds a float; default value 0.0
• x = BooleanVar() # Holds a boolean, returns 0 for False
and 1 for True

• To read the current value of such a variable, call the method


get().
• The value of such a variable can be changed with the set()
method.
Tkinter IntVar() Function

• A variable defined using IntVar() function


holds integer data where we can set integer
data and can retrieve it as well using getter
and setter methods.
from tkinter import *

Radiobutton def sel():


selection = "You selected the option " + str(var.get())
label.config(text = selection)

• program7 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()
Code
• # Use Radiobutton in tkinter
• from tkinter import *
• root = Tk()
• x = IntVar()
• R1 = Radiobutton(root, text="Option 1", variable = x, value =1)
• R1.pack()

• R2 = Radiobutton(root, text="Option 2", variable = x, value =2)


• R2.pack()

• R3 = Radiobutton(root, text="Option 3", variable = x, value =3)


• R3.pack()

• mainloop()
Menubutton
• The Menubutton widget can be defined as
the drop-down menu
that is shown to the user all the time.
Menubutton
• Place Menu ( ) in Tk
• Now config()
• Use add_command()

• t1= Menubutton (parent_window, options)


• program8
Menubutton
#Menubutton in tkinter
from tkinter import *
top = Tk()
top.geometry("200x700")
mb= Menubutton(text="Hobbies")
a = Menu(mb , tearoff=1 )
mb["menu"] = a

x1 = IntVar()
y1 = IntVar()

a.add_checkbutton ( label="Music", variable= x1)


a.add_checkbutton ( label="Programming", variable= y1)

mb.place(x=100, y=100)
mainloop()
Use add_command, add_cascade
to config a menu
Checkbutton
• The Checkbutton widget is used to display a
number of options to a user as toggle buttons.
The user can then select one or more options
by clicking the button corresponding to each
option.

• w = Checkbutton ( master, option, ... )


Check button
#USE of Checkbutton

from tkinter import *


from tkinter import messagebox

top = Tk()

CheckVar1 = IntVar()
CheckVar2 = IntVar()

C1 = Checkbutton(top, text = "Music", variable = CheckVar1, offvalue = 1, height=5,


width = 20, selectcolor="red")
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, height=5,
width = 50)

C1.pack()
C2.pack()
mainloop()

#offvalue =1 means always active(always On signal)


Spinbox
• A Spinbox widget allows you to select a value from a set of
values. The values can be a range of numbers.
• A Spinbox has an area for showing the current value and a pair
of arrowheads.
• When you click the upward-pointing arrowhead, the Spinbox
advances the current value to the next higher value in the
sequence. If the current value reaches the maximum value,
you can set it to the minimum value.
• On the other hand, if you click the downward-pointing
arrowhead, the Spinbox advances the current value to the
next lower value in the sequence. If the current value reaches
the lowest value, you can set it to the maximum value.
• Also, you can enter a value directly into the Spinbox widget as
if it were an Entry widget.
Spinbox
• # USe Spinbox
• from tkinter import *
• root = Tk()
• c=IntVar()

• sp = Spinbox(root, from_ = 0, to = 30, wrap = True)

• sp.pack()
• mainloop()
wrap
• The wrap is a Boolean value.
• If wrap equals True , when the current value
reaches the maximum value, it's set to the
lowest value if you click the upward-pointing
arrowhead and vice versa.
• In case wrap equals False , it's set to the
maximum value if you click the downward-
pointing arrowhead.
Scale
• The Scale widget provides a graphical slider
object that allows you to select values from a
specific scale.
• Syntax
w = Scale ( master, option, ... )
Message
• This widget provides a multiline and non-
editable object that displays texts,
automatically breaking lines and justifying
their contents.
• Its functionality is very similar to the one
provided by the Label widget, except that it
can also automatically wrap the text,
maintaining a given width or aspect ratio.
Image
• To display images in labels, buttons, canvas,
and text widgets, the PhotoImage class is
used, which is present in tkinter package.
• "PhotoImage()" function returns the image
object.
import PIL
• PIL is the Python Imaging Library which
provides the python interpreter with image
editing capabilities.
• # Use images as Label
• from tkinter import *
• from PIL import Image, ImageTk # PIL is Python Imaging Library
• root = Tk()

• mg = Image.open("abc.gif") # import Image

• # Resize the image using resize() method
• mg1 = mg.resize((30, 30)) #use resize

• im = ImageTk.PhotoImage(mg1)
• x = Label(image = im)
• x.image = im
• x.pack()
• mainloop()
Bring Image
from tkinter import *
top = Tk()
Program
#Import the image using PhotoImage function
im= PhotoImage(file='abc.gif')

bt= Labe l(top, image=im, borderwidth=0)


bt.pack()

mainloop()
Images at Buttons
• A bitmap is an array of binary data
representing the values of pixels in an image.
A GIF is an example of a graphics image file
that has a bitmap.
• To create a bitmap image ‘bitmap’ attribute of
the button() function is used display. It can
take the following values:
• # Use images as Label, 2 different images at two labels
• from tkinter import *
• from PIL import Image, ImageTk # PIL is Python Imaging Library
• root = Tk()
• root.geometry("500x500")
• mg = Image.open('abc.gif') # import Image
• mg1 = Image.open('D:\py.gif')
• mg = mg.resize((70, 70)) #use resize
• mg1 = mg1.resize((70, 70))
• im = ImageTk.PhotoImage(mg)
• im1 = ImageTk.PhotoImage(mg1)
• x = Label(image = im)
• y = Label(image = im1)
• x.image = im
• y.image = im1
• x.pack(side=LEFT)
• y.pack(side=RIGHT)
• mainloop()
Easy Code of Popular bitmaps at
buttons
• #images at Buttons (use bitmap)
• from tkinter import *
• root = Tk()
• Button(bitmap="question").pack(pady=30)
• Button(bitmap="questhead").pack(pady=10)
• Button(bitmap="warning"). pack(pady=30)
• Button(bitmap="error") . pack(pady=10)
• Button(bitmap="info").pack(pady=10)
• mainloop()
• #images at Buttons (use bitmap)
• from tkinter import *
• root = Tk()
• Button(root, relief=GROOVE, bitmap="question", bd=10).pack(pady=30)

• Button(root, relief=RAISED, bitmap="warning").pack(pady=30)


• Button(root, relief=RAISED, bitmap="gray75").pack(pady=10)
• Button(root, relief=RAISED, bitmap="gray50").pack(pady=10)
• Button(root, relief=RAISED, bitmap="gray25").pack(pady=10)
• Button(root, relief=RAISED, bitmap="gray12").pack(pady=10)
• Button(root, relief=RAISED, bitmap="questhead").pack(pady=10)
• Button(root, relief=RAISED, bitmap="error").pack(pady=10)
• Button(root, relief=RAISED, bitmap="hourglass").pack(pady=10)
• Button(root, relief=RAISED, bitmap="info").pack(pady=10)
• root.mainloop()

You might also like