0% found this document useful (0 votes)
167 views

Tkinter - Students 4 UNIT CH2 GUI Using Python

This document discusses Tkinter, the standard GUI library for Python. It provides an overview of Tkinter and describes how to create basic GUI elements like buttons, labels, entries, canvases, and more using Tkinter. It also covers layout managers like pack(), grid(), and place(); Tkinter widget attributes; and important functions like mainloop() and Tk(). Overall the document serves as a tutorial for beginners on how to build GUI applications in Python using Tkinter.

Uploaded by

Deependra
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

Tkinter - Students 4 UNIT CH2 GUI Using Python

This document discusses Tkinter, the standard GUI library for Python. It provides an overview of Tkinter and describes how to create basic GUI elements like buttons, labels, entries, canvases, and more using Tkinter. It also covers layout managers like pack(), grid(), and place(); Tkinter widget attributes; and important functions like mainloop() and Tk(). Overall the document serves as a tutorial for beginners on how to build GUI applications in Python using Tkinter.

Uploaded by

Deependra
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

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
– cursors
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 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
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
Examples: Button, Label
#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 ***
import tkinter as tk

win = tk.Tk()
win.geometry("500x500+10+20")
# add an orange frame
frame1 = tk.Frame(master=win, width=100, height=100, bg="pink")
frame1.pack()

# add blue frame


frame2 = tk.Frame(master=win, width=50, height=50, bg="grey")
frame2.pack()

# add green frame


frame3 = tk.Frame(master=win, width=25, height=25, bg="green")
frame3.pack()

window.mainloop()
Button and apply tkMessageBox
• Program2
on its command
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")

ob = Tkinter.Button(top, text ="Hello", command = helloCallBack)


ob.pack()
top.mainloop()
Canvas
• The Canvas is a rectangular area intended for
drawing pictures or other complex layouts.
You 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()
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()
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, listvariable)
to create a Listbox widget;
• a listvariable should be a StringVar(value=items).

• Bind a callback function to the '<<ListboxSelect>>' event to


execute the function when one or more list items are
selected.
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
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()
Tkinter IntVar() Function

• These variables also contain getter and setter


methods to access and change their values.
IntVar is an example of them.
• 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()
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
from tkinter import *
import tkMessageBox
import tkinter
top = Tk()
mb= Menubutton ( top, text="condiments“,relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu

mayoVar = IntVar()
ketchVar = IntVar()

mb.menu.add_checkbutton ( label="mayo",
variable=mayoVar )
mb.menu.add_checkbutton ( label="ketchup",
variable=ketchVar )
mb.pack()
top.mainloop()
Check button
from Tkinter import *
import tkMessageBox
program9 import Tkinter

top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1,
onvalue = 1, offvalue = 0, height=5, width = 20)
C2 = Checkbutton(top, text = "Video", variable = CheckVar2,
onvalue = 1, offvalue = 0, height=15, width = 50)
C1.pack()
C2.pack()
top.mainloop()
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.
Bring Image
# Putting a gif image on a canvas with tkinter

Program from tkinter import *


root=Tk()
# create the canvas, size in pixels
canvas = Canvas(width = 300, height = 200, bg = 'yellow')
# pack the canvas into a frame/form
canvas.pack(expand = YES, fill = BOTH)
# load the .gif image file
# put in your own gif file here, may need to add full path
gif1 = PhotoImage(file = 'dw.gif')
# put gif image on canvas
# pic's upper left corner (NW) on the canvas is at x=50 y=10
canvas.create_image(50, 10, image = gif1, anchor = NW)
# run it ...
root.mainloop()
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.
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.

You might also like