Jabon Lex6.0
Jabon Lex6.0
College of Engineering
Name: Emanuel B. Jabon Course/Year/Section: BSCPE 1-1 Date: June 10, 2023
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.
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
def clicked():
print("Button Pressed!")
app = Tk()
app.title("Modified GUI Example")
app.geometry('400x300')
app.mainloop()
2
Exercise 2: Adding a Label and Entry Widget
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.
# Create a button
button_change = Button(window, text="Change Text", command=changeLabelText)
# Create a label
label_text = Label(window, text="Open")
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.
# Create a button
button1 = Button(bottom_panel, text="Submit", command=clicked)
button1.pack()
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
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')
entry = Entry(app)
entry.pack()
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
app = Tk()
app.title("Layout Example")
app.geometry('400x200')
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
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)
# 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:
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
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")
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:
# 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
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)
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)
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)
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)
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:
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)
11
app.mainloop()
Output:
• 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
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)
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.
Code:
#LEX 6.0 - Exercise 5.3
#Programmed by: Emanuel Jabon BSCPE 1-1
# Variables
fileName = None
fileContents = None
fileChanged = False
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
app.mainloop()
Output:
15