0% found this document useful (0 votes)
31 views15 pages

Jabon Lex6.0

1. The document provides exercises for learning GUI programming in Python using Tkinter. It includes exercises to create basic GUI elements like buttons and labels, handling events, and managing layouts. 2. Later exercises involve adding additional elements like entry widgets, modifying programs to change text and attributes when buttons are pressed, and drawing shapes on a canvas when the mouse is clicked in different locations. 3. Layout management is practiced by arranging labels in a grid and making them resize responsive. Drawing on a canvas is explored by drawing different shapes and colors based on key presses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views15 pages

Jabon Lex6.0

1. The document provides exercises for learning GUI programming in Python using Tkinter. It includes exercises to create basic GUI elements like buttons and labels, handling events, and managing layouts. 2. Later exercises involve adding additional elements like entry widgets, modifying programs to change text and attributes when buttons are pressed, and drawing shapes on a canvas when the mouse is clicked in different locations. 3. Layout management is practiced by arranging labels in a grid and making them resize responsive. Drawing on a canvas is explored by drawing different shapes and colors based on key presses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES

Sta. Mesa Manila

College of Engineering

Name: Emanuel B. Jabon Course/Year/Section: BSCPE 1-1 Date: June 10, 2023

Subject: Object Oriented Programming

Prof. Eng. Julius Cansino

Introduction to GUI Programming in Python

LEX 6.0 TKinter -GUI Application in Python

Exercise 1: A First GUI Program The following program is available for download (called
exercise1.py). Find the program, open it using IDLE and run it.

# Import the Tkinter package


# Note in Python 3 it isall lowercase
from tkinter import *
# This method is called when the button is pressed
def clicked():
print("Clicked")
# Create a main frame with
# -- a title
# - size 200 by 200 pixels
app = Tk()
app.title("GUI Example 1")
app.geometry('200x200')
# Create the button with
# - suitable text
# - a command to call when the button is pressed
button1 = Button(app, text="Click Here", command=clicked)
# Make the button visible at the bottom of the frame
button1.pack(side='bottom')
# Start the application running
app.mainloop()

Output:

1
Exercise 1.2: Modify the Program

Although it has not been explained yet, see if you can figure out how to make
the following modifications:
• Change the title
• Change the text in the button
• Change the text printed when the button is pressed
• Change the size (geometry) of the rectangular frame
• Move the button to the top of the frame

Code: Modified GUI Application

#LEX 6.0 - EXERCISE 1: A First GUI Program


#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *

def clicked():
print("Button Pressed!")

app = Tk()
app.title("Modified GUI Example")
app.geometry('400x300')

button1 = Button(app, text="Press Me!", command=clicked)


button1.pack(side='top')

app.mainloop()

Output: Modified GUI Application

2
Exercise 2: Adding a Label and Entry Widget

Exercise 2.1: Part A: Getting and Setting Attributes

Run the given program (exercise2A.py); this version just has a button and a label. Pressing the
button once changes the text of the label. Change it so that the text changes on each press,
toggling between two messages.

Code: Part A: Getting and Setting Attributes


#LEX 6.0 - Exercise 2.1: Part A: Getting and Setting Attributes
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *

# Create the main window


window = Tk()
window.title("Label and Button Example")
window.geometry('200x100')

# Function to change the label text


def changeLabelText():
if label_text['text'] == "Open":
label_text['text'] = "Close"
else:
label_text['text'] = "Open"

# Create a button
button_change = Button(window, text="Change Text", command=changeLabelText)

# Create a label
label_text = Label(window, text="Open")

# Place the button and label in the window


label_text.pack(side='bottom')
button_change.pack(side='bottom')

# Start the application


window.mainloop()

Output: Part A: Getting and Setting Attributes

3
Exercise 2.2: Part B: Complete Program

Run the given program (exercise2B.py); this part adds the entry widget. When you enter text in
the box (the Entry widget) and press the button, it only prints the text from the entry. Complete it
so that it behaves as described above.

Code: Part B: Complete Program


#LEX 6.0 - Exercise 2.2: Part B: Complete Program
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *

# Function to handle button click


def clicked():
input_text = entry1.get()
print("You entered:", input_text)
button1.config(text=input_text)

# Create the main window


window = Tk()
window.title("Text Input Example")
window.geometry('300x200')

# Create a frame for the bottom panel


bottom_panel = Frame(window)
bottom_panel.pack(side=BOTTOM, padx=10, pady=10)

# Create a label to prompt the user


prompt_label = Label(bottom_panel, text="Enter a word:")
prompt_label.pack()

# Create a frame for the input panel


input_panel = Frame(bottom_panel)
input_panel.pack()

# Create an entry widget for text input


entry1 = Entry(input_panel)
entry1.pack(side=LEFT)

# Create a button
button1 = Button(bottom_panel, text="Submit", command=clicked)
button1.pack()

# Start the application


window.mainloop()

Output: Part B: Complete Program

4
Exercise 2.3: Elaborations

• When the button is pressed, check if the entered text is blank (i.e. has zero length). If so,
do not copy it but instead set the background of the button red. Restore the original
background colour when the button is pressed and some text has been entered.
• After the button has been pressed and the label changed, make the next press of the
button clear the text in the entry widget. Change the button text so that the user
understands what is happening.
Code:
#LEX 6.0 - Exercise 2.3: Elaborations
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *

def buttonClicked():
inputText = entry.get()

if len(inputText) == 0:
button.config(bg='red')
else:
button.config(bg='SystemButtonFace')
label.config(text="You entered: " + inputText)
entry.delete(0, END)
button.config(text="Text Copied!")

app = Tk()
app.title("Text Input Example")
app.geometry('300x200')

labelPrompt = Label(app, text="Enter a word:")


labelPrompt.pack()

entry = Entry(app)
entry.pack()

label = Label(app, text="")


label.pack()

button = Button(app, text="Copy Text", command=buttonClicked)


button.pack(side='bottom')

app.mainloop()

Output:

5
Exercise 3: Managing Layout
Exercise 3.1: Arrange the labels is a square grid with the pack layout manager this means
introduces extra frames so that the labels are in the frames and the frames are in the top-level
window. In the diagram above, the frames have a border so they can be seen.
Code:
#LEX 6.0 - Exercise 3.1
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *


import random

app = Tk()
app.title("Layout Example")
app.geometry('400x200')

leftFrame = Frame(app, bd=5, relief=GROOVE)


rightFrame = Frame(app, bd=5, relief=GROOVE)
leftFrame.pack(side='left', fill=BOTH, expand=1)
rightFrame.pack(side='right', fill=BOTH, expand=1)

labelA = Label(leftFrame, text="A", bg='blue', width=12)


labelB = Label(leftFrame, text="B", bg='white', width=12)
labelC = Label(rightFrame, text="C", bg='white', width=12)
labelD = Label(rightFrame, text="D", bg='blue', width=12)

labelA.pack(side='top', fill=BOTH, expand=1)


labelB.pack(side='bottom', fill=BOTH, expand=1)
labelC.pack(side='top', fill=BOTH, expand=1)
labelD.pack(side='bottom', fill=BOTH, expand=1)

app.mainloop()

Output:

Exercise 3.2: Support resizing Use the ‘expand’ and ‘fill’ attributes of the pack method to make
the labels grow and expand into the available space. There is more guidance in code comments.
Code:
#LEX 6.0 - Exercise 3.2
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *


import random

app = Tk()

6
app.title("Resizable Layout Example")

# Create two frames and lay them out beside each other
leftFrame = Frame(app, bd=5, relief=GROOVE)
rightFrame = Frame(app, bd=5, relief=GROOVE)
leftFrame.pack(side='left', fill=BOTH, expand=True)
rightFrame.pack(side='right', fill=BOTH, expand=True)

# Create labels inside the frames


labelA = Label(leftFrame, text="A", bg='blue', width=12)
labelB = Label(leftFrame, text="B", bg='white', width=12)
labelC = Label(rightFrame, text="C", bg='white', width=12)
labelD = Label(rightFrame, text="D", bg='blue', width=12)

# Pack labels with expand and fill options to make them grow and expand
labelA.pack(side='top', fill=BOTH, expand=True)
labelB.pack(side='bottom', fill=BOTH, expand=True)
labelC.pack(side='top', fill=BOTH, expand=True)
labelD.pack(side='bottom', fill=BOTH, expand=True)

app.mainloop()

Output:

Exercise 4: The Drawing Canvas and Events


Exercise 4.1: Draw a Square where the mouse is clicked Instead of always drawing the same
shapes, use the mouse to draw a square: the top- left corner of the square goes where the mouse
is clicked.
Code:
#LEX 6.0 - Exercise 4.1
#Programmed by: Emanuel Jabon BSCPE 1-1

import tkinter as tk

def draw_square(event):
# Get the x and y coordinates of the mouse click event
x = event.x
y = event.y

# Set the size of the square


size = 50

# Calculate the coordinates of the square


x1 = x # x-coordinate of the top-left corner of the square
y1 = y # y-coordinate of the top-left corner of the square
x2 = x + size # x-coordinate of the bottom-right corner of the square
y2 = y + size # y-coordinate of the bottom-right corner of the square

7
# Draw the square on the canvas with a red fill color
canvas.create_rectangle(x1, y1, x2, y2, fill="red")

root = tk.Tk()
root.title("Draw Square")
root.geometry("400x400")

canvas = tk.Canvas(root, width=400, height=400)


canvas.pack()

# Bind the mouse click event to the draw_square function


canvas.bind("<Button-1>", draw_square)

root.mainloop()

Output:

Exercise 4.2: Change the shape, colour and fill.Use keys to specify the shape, colour and
whether the shape is filled. For example:

• Shape: ‘s’ for square, ‘c’ for circle


• Filling: ‘F’ for filled, ‘f’ for unfilled
• Colour: ‘y’ for yellow, ‘r’ for red
Code:
#LEX 6.0 - Exercise 4.2
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *

app = Tk() # Create the top-level window


app.title("GUI Example 5") # OPTIONALLY set the title
app.geometry('400x400') # OPTIONALLY set the size

# Create a canvas
# -----------------
# - background is blue (this is a bit odd)
# - make it as large as the main window
canvas = Canvas(app, bg='blue')
canvas.pack(expand=1, fill=BOTH)

# Event bindings
# --------------
# Bind mouse or key press events to functions

# Handler for the SHAPE key press event

8
# -------------------------------------
shape = "s"

def sKey(event):
global shape
print("Now drawing squares")
shape = "s"

def cKey(event):
global shape
print("Now drawing circles")
shape = "c"

app.bind("<KeyPress-s>", sKey)
app.bind("<KeyPress-c>", cKey)

# Handler for the FILL key press event


# -----------------------------------
fill = False

def fKey(event):
global fill
print("Now drawing unfilled shapes")
fill = False

def FKey(event):
global fill
print("Now drawing filled shapes")
fill = True

app.bind("<KeyPress-f>", fKey)
app.bind("<KeyPress-F>", FKey)

# Handler for the COLOUR key press event


# -------------------------------------
colour = "yellow"

def rKey(event):
global colour
print("Now drawing in red")
colour = "red"

def yKey(event):
global colour
print("Now drawing in yellow")
colour = "yellow"

app.bind("<KeyPress-r>", rKey)
app.bind("<KeyPress-y>", yKey)

# Handler for a mouse click event


# -------------------------------
# Draw shape at mouse click
#
# Size is fixed
X = 50
Y = 50

def mouseClick(event):
mx = event.x
my = event.y
if shape == "s":
if fill:
canvas.create_rectangle(mx, my, mx + X, my + Y, width=5,
outline=colour, fill=colour)
else:
canvas.create_rectangle(mx, my, mx + X, my + Y, width=5,
outline=colour)
else:
if fill:
canvas.create_oval(mx, my, mx + X, my + Y, width=5,
outline=colour, fill=colour)
else:
canvas.create_oval(mx, my, mx + X, my + Y, width=5,
outline=colour)

9
canvas.bind("<Button-1>", mouseClick)

app.mainloop() # Start the main loop

Output:

Exercise 4.3: Interface Design Using a pencil and paper, sketch some better interfaces to draw
shapes. Consider either a) how to show what the current drawing options are or b) alternative
ways to specify the shape, colour and filling, plus other features that could be useful.
Output:

Exercise 5: Dialogs and Menu


Exercise 5.1: Add menu items Add the new menu and menu items. At first, do not give a
command.
Code:
#LEX 6.0 - Exercise 5.1
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *


from tkinter import messagebox, filedialog

def exitApp():

10
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Exit with unsaved
changes?", default=messagebox.NO)
if ans == "yes":
app.destroy()
else:
app.destroy()

def giveHelp():
ans = messagebox.askquestion("Not Much Help", "Are you sure you need
help", default=messagebox.NO)

def aboutMsg():
messagebox.showinfo("About Exercise 6", "Application to change text file
to upper case")

def openFile():
global fileName, fileContents, fileChanged
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Overwrite unsaved
changes?", default=messagebox.NO)
if ans == "no":
return
filename = filedialog.askopenfilename(title="Choose a file to open",
filetypes=[("Text", ".txt"), ("All", "")])
if filename:
with open(filename, 'r') as file:
fileContents = file.read()
fileName = filename
fileChanged = False

def saveFile():
global fileChanged
if fileName is None:
messagebox.showerror("No file", "No file open")
elif not fileChanged:
messagebox.showinfo("No changes", "File has not changed")
else:
with open(fileName, 'w') as file:
file.write(fileContents)
fileChanged = False
messagebox.showinfo("File written", "File updated")

def upperCmd():
global fileContents, fileChanged
if fileName is None:
messagebox.showerror("No file", "No file open")
else:
fileContents = fileContents.upper()
fileChanged = True

app = Tk()
app.title("File Changer")
app.geometry('400x400')

fileName = None
fileContents = None
fileChanged = False

menuBar = Menu(app)
app.config(menu=menuBar)

fileMenu = Menu(menuBar, tearoff=0)


fileMenu.add_command(label='Open', command=openFile)
fileMenu.add_command(label='Save', command=saveFile)
fileMenu.add_command(label='Quit', command=exitApp)
menuBar.add_cascade(label="File", menu=fileMenu)

editMenu = Menu(menuBar, tearoff=0)


editMenu.add_command(label='Convert to upper', command=upperCmd)
menuBar.add_cascade(label="Edit", menu=editMenu)

helpMenu = Menu(menuBar, tearoff=0)


helpMenu.add_command(label='Help', command=giveHelp)
helpMenu.add_command(label='About', command=aboutMsg)
menuBar.add_cascade(label="Help", menu=helpMenu)

11
app.mainloop()

Output:

Exercise 5.2: Implement Functions


Implement the functions to act on the command. You can use :

• open(filename, mode) to open the file with mode 'r' and 'w'
• f.close(0 to close a file
• f.read() to read a whole file
• s.upper() to convert a string s to uppercase (returns a new string)
• f.write(string) to write a string to the file
Code:
#LEX 6.0 - Exercise 5.2
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *


from tkinter import messagebox, filedialog

def exitApp():
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Exit with unsaved
changes?", default=messagebox.NO)
if ans == "yes":
app.destroy()
else:
app.destroy()

def giveHelp():
ans = messagebox.askquestion("Not Much Help", "Are you sure you need
help", default=messagebox.NO)

def aboutMsg():
messagebox.showinfo("About Exercise 6", "Application to change text file
to uppercase")

def openFile():
global fileName, fileContents, fileChanged
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Overwrite unsaved
changes?", default=messagebox.NO)
if ans == "no":
return
fileName = filedialog.askopenfilename(title="Choose a file to open",
filetypes=[("Text", ".txt"), ("All Files", ".*")])
if fileName:
with open(fileName, 'r') as file:
fileContents = file.read()
fileChanged = False

12
def saveFile():
global fileName, fileContents, fileChanged
if not fileName:
messagebox.showerror("No file", "No file open")
return
if not fileChanged:
messagebox.showinfo("No changes", "File has not changed")
return
with open(fileName, 'w') as file:
file.write(fileContents)
fileChanged = False
messagebox.showinfo("File written", "File updated")

def upperCmd():
global fileContents, fileChanged
if not fileName:
messagebox.showerror("No file", "No file open")
return
fileContents = fileContents.upper()
fileChanged = True

app = Tk()
app.title("File Changer")
app.geometry('400x400')

fileName = None
fileContents = None
fileChanged = False

menuBar = Menu(app)
app.config(menu=menuBar)

fileMenu = Menu(menuBar, tearoff=0)


fileMenu.add_command(label='Open', command=openFile)
fileMenu.add_command(label='Save', command=saveFile)
fileMenu.add_command(label='Quit', command=exitApp)
menuBar.add_cascade(label='File', menu=fileMenu)

editMenu = Menu(menuBar, tearoff=0)


editMenu.add_command(label='Convert to Upper', command=upperCmd)
menuBar.add_cascade(label='Edit', menu=editMenu)

helpMenu = Menu(menuBar, tearoff=0)


helpMenu.add_command(label='Help', command=giveHelp)
helpMenu.add_command(label='About', command=aboutMsg)
menuBar.add_cascade(label='Help', menu=helpMenu)

app.mainloop()

Output:

13
Exercise 5.3: Add checks
Add checks so that a) the program never crashes and b) the user does not lose work. The
following table suggest which checks are needed. Display suitable messages in each case.

Command Checks Needed


Open Check for unsaved changes to the current file (Question)
Save Check a file is open (Error) Check that changes need saving (Info)
Quit Check for unsaved changes to the current file (Question)
Convert to Upper Check a file is open (Error)

Code:
#LEX 6.0 - Exercise 5.3
#Programmed by: Emanuel Jabon BSCPE 1-1

from tkinter import *


from tkinter import messagebox, filedialog

# Create the main application window


app = Tk()
app.title("File Changer")
app.geometry('400x400')

# Variables
fileName = None
fileContents = None
fileChanged = False

# Create handlers for menu items


def exitApp():
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Exit with unsaved
changes?", default=messagebox.NO)
if ans == "yes":
app.destroy()
else:
app.destroy()

def giveHelp():
ans = messagebox.askquestion("Not Much Help", "Are you sure you need
help?", default=messagebox.NO)

def aboutMsg():
messagebox.showinfo("About File Changer", "This application converts a
text file to uppercase.")

def openFile():
global fileName, fileContents, fileChanged
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Discard changes and
open a new file?", default=messagebox.NO)
if ans == "no":
return
filename = filedialog.askopenfilename(title="Choose a file to open",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
if filename:
try:
with open(filename, 'r') as file:
fileContents = file.read()
fileName = filename
fileChanged = False
except:
messagebox.showerror("File Error", "Failed to open the file.")

def saveFile():
global fileName, fileContents, fileChanged
if not fileName:
messagebox.showerror("No File", "No file open.")
return
if not fileChanged:
messagebox.showinfo("No Changes", "The file has not changed.")

14
return
try:
with open(fileName, 'w') as file:
file.write(fileContents)
fileChanged = False
messagebox.showinfo("File Saved", "File successfully saved.")
except:
messagebox.showerror("File Error", "Failed to save the file.")

def upperCmd():
global fileContents, fileChanged
if not fileName:
messagebox.showerror("No File", "No file open.")
return
if fileChanged:
ans = messagebox.askquestion("Unsaved Changes", "Discard changes and
convert to uppercase?", default=messagebox.NO)
if ans == "no":
return
fileContents = fileContents.upper()
fileChanged = True

# Create menu bar and menus


menuBar = Menu(app)
app.config(menu=menuBar)

fileMenu = Menu(menuBar, tearoff=0)


fileMenu.add_command(label='Open', command=openFile)
fileMenu.add_command(label='Save', command=saveFile)
fileMenu.add_command(label='Quit', command=exitApp)
menuBar.add_cascade(label='File', menu=fileMenu)

editMenu = Menu(menuBar, tearoff=0)


editMenu.add_command(label='Convert to Uppercase', command=upperCmd)
menuBar.add_cascade(label='Edit', menu=editMenu)

helpMenu = Menu(menuBar, tearoff=0)


helpMenu.add_command(label='Help', command=giveHelp)
helpMenu.add_command(label='About', command=aboutMsg)
menuBar.add_cascade(label='Help', menu=helpMenu)

app.mainloop()

Output:

15

You might also like