Unit5 PP
Unit5 PP
Unit5 PP
PYTHON P R O G R A M M I N G
Course Code : 10211CS213
Course Name : Python Programming
Course Faculty : Mrs. M. Divya
Category : Program Core
Slot Number : S3L18
Unit : V
School of Computing
Vel Tech Rangarajan Dr. Sagunthala R&D Institute of
Science and Technology
10/17/2024 1
UNIT 5 UI and Game design using Python
libraries
2
October 17, 2024 Python Programming
Tkinter: Introduction
➢ Python provides the standard library Tkinter for creating the graphical user interface
for desktop based applications.
➢ Tkinter was written by Guido van Rossum and Steen Lumholt, later revised by Fredrik
Lundh. Tkinter is free software released under a Python license.
➢ Developing desktop based applications with python Tkinter is not a complex task. An
empty Tkinter top-level window can be created by using the following steps.
✓ import the Tkinter module.
✓ Create the main application window.
✓ Add the widgets like labels, buttons, frames, etc. to the window.
✓ Call the main event loop so that the actions can take place on the user's
computer screen.
October 17, 2024 Python Programming 3
python --version
Tkinter
◼ Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
◼ >>pip install tk
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
The Tkinter geometry specifies the method by using which, the widgets are
represented on display. The python Tkinter provides the following geometry methods.
1. The pack() method : it represents the side of the direction to which the widget,
to be placed
syntax
widget.pack(options)
2. The grid() method : it organizes the widgets in the tabular form
syntax
widget.grid(options)
3. The place() method : it places the widgets to the specific x and y coordinates.
syntax
widget.place(options)
W = Button(parent, options)
b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)
top.mainloop()
Syntax :
w = checkbutton(master, options)
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop()
Syntax :
w = Listbox(parent, options)
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top, text="A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1, "India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Australia")
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
mbutton = Menubutton(top, text="Language")
mbutton.grid()
mbutton.menu = Menu(mbutton)
mbutton["menu"] = mbutton.menu
mbutton.menu.add_checkbutton(label="Hindi", variable=IntVar())
mbutton.menu.add_checkbutton(label="English", variable=IntVar())
mbutton.pack()
October 17, 2024 Python Programming 18
Python Tkinter Menu
The Menu widget is used to create various types of menus (top level, pull down, and pop up) in the
python application.
Syntax :
w = Menu(top, options)
top = Tk()
menubar = Menu(top)
file = Menu(menubar)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
October 17, 2024 Python Programming 19
Python Tkinter Menu
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text=selection)
top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text="Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=selection)
R1.pack(anchor=W)
October 17, 2024 Python Programming 21
Python Tkinter Radiobutton
label = Label(top)
label.pack()
top.mainloop()
def select():
sel = "Value = " + str(v.get())
label.config(text=sel)
top = Tk()
top.geometry("200x100")
v = DoubleVar()
scale = Scale(top, variable=v, from_=1, to=50, orient=HORIZONTAL)
scale.pack(anchor=CENTER)
label = Label(top)
label.pack()
top.mainloop()
mylist.pack(side=LEFT)
sb.config(command=mylist.yview)
mainloop()
October 17, 2024 Python Programming 25
Python Tkinter Text
The Text widget is used to show the text data on the Python application. Tkinter provides us the Entry
widget which is used to implement the single line text box.
Syntax :
w = Text(top, options)
text.insert(INSERT, "Name.....")
text.insert(END, "Salary.....")
text.pack()
top.mainloop()
def open():
top = Toplevel(root)
top.mainloop()
Syntax :
w = Spinbox(top, options)
top = Tk()
top.geometry("200x200")
spin = Spinbox(top, from_=0, to=25)
spin.pack()
top.mainloop()
Syntax :
w = Spinbox(top, options)
# !/usr/bin/python3
from tkinter import *
def add():
a = int(e1.get())
b = int(e2.get())
leftdata = str(a + b)
left.insert(1, leftdata)
October 17, 2024 Python Programming 29
Tkinter PanedWindow
w1 = PanedWindow()
w1.pack(fill=BOTH, expand=1)
w2 = PanedWindow(w1, orient=VERTICAL)
w1.add(w2)
e1 = Entry(w2)
e2 = Entry(w2)
w2.add(e1)
w2.add(e2)
mainloop()
October 17, 2024 Python Programming 30
Tkinter LabelFrame
• The LabelFrame widget is used to draw a border around its child widgets.
• It acts like a container which can be used to group the number of interrelated widgets such as
Radiobuttons.
• This widget is a variant of the Frame widget which has all the features of a frame. It also can display a
label.
Syntax :
w = LabelFrame(top, options)
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("300x200")
top.mainloop()
Syntax :
messagebox.function_name(title, message [, options])
Parameters
➢ function_name: It represents an appropriate message box function.
➢ title: It is a string which is shown as a title of a message box.
➢ message: It is the string to be displayed as a message on the message box.
➢ options: There are various options which can be used to configure the
message dialog box.
#showwarning() method
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showwarning("warning","Warning")
top.mainloop() 1
October 17, 2024 Python Programming 34
Tkinter messagebox
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("500x500")
messagebox.showerror("error","Error")
messagebox.askquestion("Confirm","Are you sure?")
messagebox.askokcancel("Redirect","Redirecting you to www.veltech.edu.in")
messagebox.askyesno("Application","Got It?")
messagebox.askretrycancel("Application","try again?")
top.mainloop()
Gaming – Introduction
10/17/2024 36
GAMING - INTRODUCTION
GUI Vs CLI
Play Area:
❖ Display Area (Canvas) SA1 SA2
❖ Surface area (Objects that gets placed Display Area
in display area)
Pygame is rarely used in Gaming Industry.
10/17/2024 37
PYGAME – Background and Setup
10/17/2024 38
PYGAME INSTALLATION, IMPORT AND INTIALIZATION
Intiallizing Pygame
pygame.init() # starts up pyGame
10/17/2024 39
Setting up Screen for your game
fill((R, G, B))
This method is used to fill the display with the color specified.
• Argument: (Red, Green, Blue)
➔ RGB values to set the background color
(0, 0, 0) ➔ Black
(255, 255, 255) ➔ White
win.fill((0,0,0))
10/17/2024 40
GAME STATES AND GAME LOOP
Game State:
Refers to a set of values for all the variables in a game program.
Event:
(Clicking a mouse, Pressing a key) which affects the game state
Game state is usually updated in response to events
or the passage of time.
Game Loop
1. Handles events.
2. Updates the game state.
3. Draws the game state to the screen.
1. Event Handling:
The main code that updates the game state based on which events have been created.
To identify the event: pygame.event.get()
Returns ➔ a list of pygame.event.Event objects
10/17/2024 41
Pygame functions – Update and Exit conditions
2. Draws the Surface object and updates the display:
pygame.display.update()
10/17/2024 42
Pygame functions – Inserting Images
Image module in pygame is for image transfer
Loads new image from a file (or file-like object)
returns ➔ Surface. The returned Surface will contain the same color
format, colorkey and alpha transparency as the file it came from.
10/17/2024 43
Pygame functions
Example:
catImg = pygame.image.load('F:\VTU\B.Tech_Python\
course_ready\pics\cat.png')
win.blit(catImg, (0, 0))
win.blit(catImg, (400, 400))
Handling Events:
pygame.key.get_pressed()
Returns ➔ A sequence of boolean values representing the state of every key on the
keyboard.
10/17/2024 44
Sample Game: Catch the Cat
# Simple pygame program
# Import and initialize the pygame library
import pygame
pygame.init()
vel = 5
run = True
x=0
y=0
#Game Loop
while run:
#Setting the response time for the Event
pygame.time.delay(100)
# Look at every event in the queue
for event in pygame.event.get():
# Did the user click the window close button?
if event.type == pygame.QUIT:
run = False
10/17/2024 45
#Gets the state of all keyboard buttons
keys = pygame.key.get_pressed()
#If Left Arrow Key is Pressed
if keys[pygame.K_LEFT]:
x -= vel
#If Right Arrow Key is Pressed
if keys[pygame.K_RIGHT]:
x += vel
#If Up Arrow Key is Pressed
if keys[pygame.K_UP]:
y -= vel
#If Down Arrow Key is Pressed
if keys[pygame.K_DOWN]:
y += vel
#Fill the display with specified color
win.fill((0,0,0))
#Blit the Images to the Display Surfce(Canvas)
catImg = pygame.image.load('F:\VTU\B.Tech_Python\Course_ready\pics\cat.png')
win.blit(catImg, (x, y))
win.blit(catImg, (400, 400))
#Update the display
pygame.display.update()
10/17/2024 46
Thank You
Any Queries