Engr. RANEL O. PADON XIII. GUI PROGRAMMING
PYTHON PROGRAMMING TOPICS I • Introduction to Python Programming II • Python Basics III • Controlling the Program Flow IV • Program Components: Functions, Classes, Packages, and Modules V • Sequences (List and Tuples), and Dictionaries VI • Object-Based Programming: Classes and Objects VII • Customizing Classes and Operator Overloading VIII • Object-Oriented Programming: Inheritance and Polymorphism IX • Randomization Algorithms X • Exception Handling and Assertions XI • String Manipulation and Regular Expressions XII • File Handling and Processing XIII • GUI Programming Using Tkinter
PYTHON GUI: TKINTER Python Operating System
PYTHON GUI: TKINTER Python Tcl Tk Operating System
PYTHON GUI: TKINTER Python Tcl Tk Operating System Tkinter
PYTHON GUI: TKINTER Tkinter Operating System
PYTHON GUI: TKINTER Tkinter = Tcl + Tk
PYTHON GUI: TKINTER = Tcl + Tk Tcl: Tool Command Language invented in 1990 used for web and desktop applications, networking, administration, scripted applications, embedded system, rapid prototyping and testing.
PYTHON GUI: TKINTER = Tcl + Tk Tcl: Tool Command Language Interfacing with other Languages q  Tcl/C++ q  Tcl/Java
PYTHON GUI: TKINTER = Tcl + Tk Tcl: Tool Command Language allows extension packages, which provide additional functionality, such as a GUI, terminal-based application automation, database access, etc. q  Tcl/Tk q  Tcl/Expect
PYTHON GUI: TKINTER = Tcl + Tk Tk: ToolKit open-source, cross platform widget toolkit for building GUI other common widgets are: * Java AWT and Java Swing (OpenOffice) * Qt (Google Earth, Skype, Linux KDE windows) * GTK+ (Linux Gnome windows) * Cocoa (Mac OS) * Silverlight (modern MS Windows NT)
PYTHON GUI: TKINTER = Tcl + Tk Tk: ToolKit created originally for Tcl other language bindings also exist: * Python/Tk = Tkinter * Perl/Tk * Ruby/Tk
PYTHON GUI: TKINTER = Tcl + Tk Tkinter: Tk Interface * wrapper for Tcl to access Tk * Python and Tcl could co-exist in a Python file. * Python interpreter also contains Tcl and Tk interpreter
PYTHON GUI: TKINTER Related Projects Language Widget Toolkit Java Abstract Windowing Toolkit Swing PHP PHP - GTK PHP - Qt Javascript jQuery UI ExtJS Python Tkinter Pyjamas PyGTK PyQt PySide wxPython
PYTHON GUI: TKINTER Related Projects (Java’s Swing with Nimbus Theme)
PYTHON GUI: TKINTER = Tcl + Tk
PYTHON GUI: TKINTER = Tcl + Tk Tk A GUI toolkit provided as a library of C routines. This library manages and manipulates the windows and handles the GUI events and user interaction. Tcl The (mostly hidden) language used by Tk and, hence, used by Tkinter to communicate with the Tk toolkit. Tkinter The Python Tk interface. A Python module that provides a collection of Python classes and methods for accessing the Tk toolkit from within Python.
PYTHON GUI: TKINTER Widget A user interface element (text box, combo box, or top-level window). On Windows, the common terminology is control or window.
PYTHON GUI: Pros Brevity Python programs using Tkinter can be very brief, partly because of the power of Python, but also due to Tk. Reasonable default values are defined for many options used in creating a widget, and packing it (i.e., placing and displaying).
PYTHON GUI: Pros Cross platform Tk provides widgets on Windows, Macs, and most Unix implementations with very little platform-specific dependence. Some newer GUI frameworks are achieving a degree of platform independence, but it will be some time before they match Tk's in this respect.
PYTHON GUI: Pros Maturity First released in 1990, the core is well developed and stable.
PYTHON GUI: Pros Extensibility Many extensions of Tk exist, and more are being frequently distributed on the Web. Any extension is immediately accessible from Tkinter, if not through an extension to Tkinter, then at least through Tkinter's access to the Tcl language.
PYTHON GUI: Cons Speed Most calls to Tkinter are formatted as a Tcl command (a string) and interpreted by Tcl from where the actual Tk calls are made. This theoretical slowdown caused by the successive execution of two interpreted languages is rarely seen in practice and most real-world applications spend little time communicating between the various levels of Python, Tcl, and Tk.
PYTHON GUI: Cons Tcl Python purists often balk at the need to install another scripting language in order to perform GUI tasks. There is periodic interest in removing the need for Tcl by using Tk's C-language API directly, although no such attempt has ever succeeded.
PYTHON GUI: TKINTER Python Widget (Window Gadget) Subclasses
PYTHON GUI: TKINTER Python Widgets
from	Tkinter	import	* Frame().mainloop() PYTHON GUI: Frame
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	Frame.__init__(self)	self.pack() GuiTest().mainloop() PYTHON GUI: Frame
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	Frame.__init__(self)	self.pack()	self.master.title("Ranel's	Lugawan") GuiTest().mainloop() PYTHON GUI: Frame
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	Frame.__init__(self)	self.pack()	self.master.title("Ranel's	Lugawan")	self.label	=	Label(self,	text	=	"Ako	ang	Simula")	self.label.pack() GuiTest().mainloop() PYTHON GUI: Label
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.text	=	Entry(self,	name	=	“butas”)	self.text.pack() GuiTest().mainloop() PYTHON GUI: Entry
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.text	=	Entry(self,	name	=	“butas”)	self.text.bind("<Return>",	self.anoLaman)	self.text.pack() def	anoLaman(self,	propeta):	print	"ang	laman	ay",	propeta.widget.get() PYTHON GUI: Event Binding
from	Tkinter	import	* from	tkMessageBox	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.text	=	Entry(self,	name	=	“butas")	self.text.bind("<Return>",	self.anoLaman)	self.text.pack() def	anoLaman(self,	propeta):	showinfo() PYTHON GUI: Message Box
from	Tkinter	import	* from	tkMessageBox	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.text	=	Entry(self,	name	=	“butas")	self.text.bind("<Return>",	self.anoLaman)	self.text.pack() def	anoLaman(self,	propeta):	pangalan	=	propeta.widget.winfo_name()	laman	=	propeta.widget.get()	showinfo("Message",	pangalan+"	:	"+laman) PYTHON GUI: Message Box
from	Tkinter	import	* from	tkMessageBox	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.text	=	Entry(self,	name	=	“butas")	self.text.bind("<Return>",	self.anoLaman)	self.text.insert(INSERT,	“Ano	ang	misyon	mo?")	self.text.pack() def	anoLaman(self,	propeta):	pangalan	=	propeta.widget.winfo_name()	laman	=	propeta.widget.get()	showinfo("Message",	pangalan	+	"	:	"	+	laman) PYTHON GUI: Entry Insert Function
from	Tkinter	import	* from	tkMessageBox	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.button	=	Button(self,	text	=	"Koya	wag	po!",	command	=	self.pinindot)	self.button.pack() def	pinindot(self):	showinfo("Mensahe",	"Bakit	nyo	ako	pinindot?	:(") PYTHON GUI: Button
from	Tkinter	import	* class	GuiTest(Frame):	def	__init__(self):	…	self.button	=	Button(self,	text	=	"Koya	wag	po!",	command	=	self.pinindot)	self.button.bind("<Enter>",	self.iLubog)	self.button.bind("<Leave>",	self.iAngat) self.button.pack()	def	iLubog(self,	propeta):	propeta.widget.config(relief	=	GROOVE)	def	iAngat(self,	propeta):	propeta.widget.config(relief	=	RAISED) PYTHON GUI: Button Hover
class	GuiTest(Frame):	def	__init__(self):	…	self.imageGoogle	=	PhotoImage(file	=	"google.gif")	self.buttonPic	=	Button(self,	image	=	self.imageGoogle,	command	=	self.pinindotPiktyur)	self.buttonPic.bind("<Enter>",	self.iLubog)	self.buttonPic.bind("<Leave>",	self.iAngat)	self.buttonPic.pack() def	pinindotPiktyur(self):	showinfo("Mensahe",	“Di	pa	po	kayo	bayad!") PYTHON GUI: Button with PhotoImage
PYTHON GUI: Radiobutton
PYTHON GUI: Radiobutton from	Tkinter	import	* class	ChannelButton(Frame):	… ChannelButton().mainloop()
def	__init__(self):	Frame.__init__(self)	self.master.title("Radiobutton	Demo")	self.master.geometry("250x60")	self.pack(expand	=	YES,	fill	=	BOTH)	self.laman	=	Entry(self,	width	=	60,	justify	=	CENTER)	self.laman.insert(INSERT,	"Ano	ang	paborito	mong	Channel?")	self.laman.config(state	=	DISABLED)	self.laman.pack(padx	=	5,	pady	=	5) PYTHON GUI: Radiobutton
def	__init__(self):	…	listahanNgChannels	=	["GMA","ABS-CBN","TV-5","DZUP"]	self.napilingChannel	=	StringVar()	self.napilingChannel.set("DZUP")	for	istasyon	in	listahanNgChannels:	isangButones	=	Radiobutton(self,	text	=	istasyon,	value	=	istasyon,	variable	=	self.napilingChannel,	command	=	self.ipakitaAngNapili)	isangButones.pack(side=LEFT,	expand=1,	fill=BOTH) PYTHON GUI: Radiobutton
def	__init__(self):	… def	ipakitaAngNapili(self):	print	self.napilingChannel.get()	if	self.napilingChannel.get()	==	"GMA":	showinfo("Tagline",	"Kapuso")	elif	self.napilingChannel.get()	==	"ABS-CBN":	showinfo("Tagline",	"Kapamilya")	elif	self.napilingChannel.get()	==	"TV-5":	showinfo("Tagline",	"Kapatid")	else:	showinfo("Tagline",	"Itanong	Mo	Kay	Engr:	Every	Monday	@	4-5pm!") PYTHON GUI: Checkbutton
PYTHON GUI: Checkbutton
from	Tkinter	import	* class	CheckbuttonTest(Frame):	… CheckbuttonTest().mainloop() PYTHON GUI: Radiobutton
def	__init__(self):	Frame.__init__(self)	self.master.title("Check	Box	Demo")	self.master.geometry("200x50")	self.pack(expand	=	YES,	fill	=	BOTH)	self.laman	=	Entry(self,	width	=	20,	font	=	"Arial	10",	justify	=	CENTER)	self.laman.insert(INSERT,	"Tagilid	at	Makapal")	self.laman.pack(padx	=	5,	pady	=	5) PYTHON GUI: Radiobutton
def	__init__(self):	…	self.makapalBa	=	BooleanVar()	self.tsekbaksMakapal	=	Checkbutton(self,	text	=	“Pakapalin”,	variable	=	self.makapalBa,	command	=	self.baguhinAngFont)	self.tsekbaksMakapal.pack(side	=	LEFT,	expand	=	YES,	fill	=	X) PYTHON GUI: Checkbutton
def	__init__(self):	…	self.tagilidBa	=	BooleanVar()	self.tsekbaksTagilid	=	Checkbutton(self,	text	=	"Itagilid",	variable	=	self.tagilidBa,	command	=	self.baguhinAngFont)	self.tsekbaksTagilid.pack(side	=	LEFT,	expand	=	YES,	fill	=	X) PYTHON GUI: Checkbutton
def	__init__(self):	… def	baguhinAngFont(self):	hitsuraNgLaman	=	"Arial	10"	if	self.makapalBa.get():	hitsuraNgLaman	+=	"	bold"	if	self.tagilidBa.get():	hitsuraNgLaman	+=	"	italic"	self.laman.config(font	=	hitsuraNgLaman) PYTHON GUI: Checkbutton
PYTHON GUI: Checkbutton
from	Tkinter	import	* class	TikbalangCheckbutton(Frame):	… TikbalangCheckbutton().mainloop() PYTHON GUI: Radiobutton
def	__init__(self):	Frame.__init__(self)	self.master.title("Checkbutton	Tikbalang	Demo")	self.master.geometry("200x50")	self.pack(expand	=	YES,	fill	=	BOTH)	self.laman	=	Entry(self,	width	=	40,	font	=	"Arial	10",	justify	=	CENTER)	self.laman.insert(INSERT,	"Hindi	Tao,	Hindi	Hayop")	self.laman.pack(padx	=	5,	pady	=	5) PYTHON GUI: Radiobutton
def	__init__(self):	…	self.taoBa	=	BooleanVar()	self.tsekbaksTao	=	Checkbutton(self,	text	=	"Tao",	variable	=	self.taoBa,	command	=	self.baguhinAngLaman)	self.tsekbaksTao.pack(side	=	LEFT,	expand	=	YES,	fill	=	X) PYTHON GUI: Checkbutton
def	__init__(self):	…	self.kabayoBa	=	BooleanVar()	self.tsekbaksKabayo	=	Checkbutton(self,	text	=	"Kabayo",	variable	=	self.kabayoBa,	command	=	self.baguhinAngLaman)	self.tsekbaksKabayo.pack(side	=	LEFT,	expand	=	YES,	fill	=	X) PYTHON GUI: Checkbutton
def	baguhinAngLaman(self):	if	self.taoBa.get()	and	self.kabayoBa.get():	self.laman.delete(0,	END)	self.laman.insert(INSERT,	"Tikbalang")	elif	self.taoBa.get()	and	not	self.kabayoBa.get():	self.laman.delete(0,	END)	self.laman.insert(INSERT,	"Tao")	elif	not	self.taoBa.get()	and	self.kabayoBa.get():	self.laman.delete(0,	END)	self.laman.insert(INSERT,	"Kabayo")	else:	self.laman.delete(0,	END)	self.laman.insert(INSERT,	"Hindi	Tao,	Hindi	Hayop") PYTHON GUI: Checkbutton
PYTHON GUI: Grid Layout
from	Tkinter	import	* class	PinasGrid(Frame):	… PinasGrid().mainloop() PYTHON GUI: Grid Layout
def	__init__(self):	Frame.__init__(self)	self.master.title("Tayo	na	sa	Pinas")	self.master.geometry("350x250")	self.pack(expand=1,	fill=BOTH)	self.hilaga	=	Button(self,	text="Hilaga",	command=self.pumuntaSaHilaga)	self.hilaga.grid(row=0,	columnspan=3,	sticky	=	W+E+N+S,	padx=5,	pady=5)	self.kanluran	=	Button(self,	text="Kanluran",	command=self.pumuntaSaKanluran)	self.kanluran.grid(row=1,	column=0,	sticky	=	W+E+N+S,	padx=5,	pady=5) PYTHON GUI: Grid Layout
def	__init__(self):	…	self.sentro	=	Label(self,	text="Tayo	na	sa	Pinas!",	foreground="blue")	self.sentro.grid(row=1,	column=1,	sticky	=	W+E+N+S)	self.silangan	=	Button(self,	text="Silangan",	command=self.pumuntaSaSilangan)	self.silangan.grid(row=1,	column=2,	sticky	=	W+E+N+S,	padx=5,	pady=5)	self.timog	=	Button(self,	text="Timog",	command=self.pumuntaSaTimog)	self.timog.grid(row=2,	columnspan=3,	sticky	=	W+E+N+S,	padx=5,	pady=5) PYTHON GUI: Grid Layout
def	__init__(self):	…	self.columnconfigure(0,	weight	=	1)	self.columnconfigure(1,	weight	=	1)	self.columnconfigure(2,	weight	=	1)	self.rowconfigure(0,	weight	=	1)	self.rowconfigure(1,	weight	=	1)	self.rowconfigure(2,	weight	=	1) PYTHON GUI: Grid Layout
def	__init__(self):	… def	pumuntaSaHilaga(self):	self.sentro.config(text	=	"Tayo	na	sa	Batanes!") def	pumuntaSaKanluran(self):	self.sentro.config(text	=	"Tayo	na	sa	Palawan!") def	pumuntaSaSilangan(self):	self.sentro.config(text	=	"Tayo	na	sa	Cebu!") def	pumuntaSaTimog(self):	self.sentro.config(text	=	"Tayo	na	sa	Sulu") PYTHON GUI: Grid Layout
PYTHON GUI: Calculator
PYTHON GUI: Calculator
PYTHON GUI: Calculator
PYTHON GUI: Calculator
from	__future__	import	division from	Tkinter	import	* class	CalcuNiRanie(Frame):	… CalcuNiRanie().mainloop() PYTHON GUI: Calculator
def	__init__(self):	Frame.__init__(self)	self.master.title("Calcu	ni	Kuya	Ranie")	self.master.geometry("250x250")	self.pack(expand=1,	fill=BOTH)	self.frame1	=	Frame(self)	self.frame1.pack(expand=0,	fill	=	BOTH)	self.screen	=	Entry(self.frame1)	self.screen.pack(expand=1,	fill	=	BOTH,	padx	=	5,	pady	=	5)	self.screen.config(justify=RIGHT,	font	=	"Arial	18") PYTHON GUI: Calculator
def	__init__(self):	…	self.frame2	=	Frame(self)	self.frame2.pack(expand=1,	fill=BOTH)	self.pito	=	Button(self.frame2,	text	=	"7",	command	=	self.pito)	self.pito.grid(row=1,	column=0,	sticky	=	W+E+N+S)	self.walo	=	Button(self.frame2,	text	=	"8",	…	self.walo.grid(row=1,	column=1,	sticky	=	W+E+N+S)	…	self.katimbang	=	Button(self.frame2,	text	=	"=",	command	=	self.anoAngSagot)	self.katimbang.grid(row=4,	column=2,	sticky	=	W+E+N+S) PYTHON GUI: Calculator
def	__init__(self):	…	self.frame2.columnconfigure(0,	weight	=	1)	self.frame2.columnconfigure(1,	weight	=	1)	self.frame2.columnconfigure(2,	weight	=	1)	self.frame2.columnconfigure(3,	weight	=	1)	self.frame2.rowconfigure(1,	weight	=	1)	self.frame2.rowconfigure(2,	weight	=	1)	self.frame2.rowconfigure(3,	weight	=	1)	self.frame2.rowconfigure(4,	weight	=	1) PYTHON GUI: Calculator
def	__init__(self):	…	def	pito(self):	self.screen.insert(END,'7')	def	walo(self):	self.screen.insert(END,'8')	…	def	anoAngSagot(self):	sagot	=	eval(self.screen.get())	self.screen.delete(0,	END)	self.screen.insert(END,	sagot) PYTHON GUI: Calculator
use the eval() function for evaluating arithmetic operations involving string parameters containing numbers >>print	eval("3	+	4") #prints	the	answer:	7 PYTHON GUI: Calculator
Python Mega Widgets (Pmw) toolkit that provides high-level GUI components from the combinations of Tkinter widgets * Menubar, ScrolledText, etc. PYTHON GUI: Pmw
Download Pmw and extract the contents of src folder to a folder e.g. extract to: C:Pyhon27src PYTHON GUI: Pmw Run the setup.py executable file in Command Prompt (install is a command-line parameter of setup.py ):
It means it could not find a python.exe file to run setup.py, hence you must add the Path of python interpreter/executable file to the System Path in the Environment variables. For example add:	;C:Pyhon27 to the list of Path of your operating system’s Environment Variables. PYTHON GUI: Pmw
Detailed Step for Adding Python to Environment Variables: right-click Computer > Properties > Advanced System Settings > Advanced > Environment Variables double-click the Path in the list of System Variables append the location of python.exe (usually located in C:Python27)	;C:Python27 Click OK to all window dialog options. Then, be sure to restart the command prompt!!! PYTHON GUI: Pmw
PYTHON GUI: Pmw.ScrolledText Type some text in the text field and it should be inserted in the scrollable, text area below it.
PYTHON GUI: Pmw.ScrolledText from	Tkinter	import	* import	Pmw class	LakasNgScrolledText(Frame):	… LakasNgScrolledText().mainloop()
def	__init__(self):	Frame.__init__(self)	Pmw.initialise()	self.pack()	self.master.geometry("150x100")	self.butas	=	Entry(self)	self.butas.bind("<Return>",	self.iTeleport)	self.butas.pack()	self.dingding	=	Pmw.ScrolledText(self,	text_width	=	25,	text_height	=	12,	text_wrap	=	WORD)	self.dingding.pack(side=BOTTOM,	expand=1,	fill=BOTH,	padx=5,	pady=5) PYTHON GUI: Pmw.ScrolledText S not Z!
def	__init__(self):	… def	iTeleport(self,	propeta):	lamanNgButas	=	propeta.widget.get()	self.butas.delete(0,	END)	#	This	line	has	similar	result	to	the	one	below	#	self.dingding.insert(END,	lamanNgButas	+	"n”)	self.dingding.settext(self.dingding.get()	+	lamanNgButas) PYTHON GUI: Pmw.ScrolledText
PYTHON GUI: Pmw.Menubar
PYTHON GUI: Pmw.Menubar from	Tkinter	import	* import	Pmw import	tkMessageBox class	TindahanNiBudoy	(Frame):	… TindahanNiBudoy().mainloop()
def	__init__(self):	Frame.__init__(self)	Pmw.initialise()	self.master.geometry("300x200")	self.pack(expand=1,	fill=BOTH)	self.sabitanNgPaninda	=	Pmw.MenuBar(self)	self.sabitanNgPaninda.pack(fill=X)	self.sabitanNgPaninda.addmenu("Mga	Paninda","Bili	na")	self.sabitanNgPaninda.addmenuitem("Mga	Paninda",	"command",	label	=	"Lugaw",	command	=	self.initinAngLugaw)	self.sabitanNgPaninda.addcascademenu("Mga	Paninda",	"Chichiria") PYTHON GUI: Pmw.Menubar
def	__init__(self):	…	self.mayBoyBawang	=	BooleanVar()	self.sabitanNgPaninda.addmenuitem("Chichiria", "checkbutton",	label	=	"Boy	Bawang",	command	=	self.idagdagAngBoyBawang,	variable	=	self.mayBoyBawang) PYTHON GUI: Pmw.Menubar
def	__init__(self):	… def	initinAngLugaw(self):	tkMessageBox.showinfo(None,	"Unlimited	Lugaw	for	P20!") def	idagdagAngBoyBawang(self):	if	self.mayBoyBawang.get():	tkMessageBox.showinfo(None,	"Boy	Bawang	toppings	on	the	go!") PYTHON GUI: Pmw.Menubar
PYTHON GUI: Other Tk functionalities 1. File Dialog for file handling 2. Closing inner and main windows 3. Drawing on Canvas widget (lines, text, ovals, etc) 4. Sliding/Adjusting values using the Scale widget 5. Animating Shapes/Blinking Rectangle
PYTHON GUI: FileDialog
PYTHON GUI: FileDialog from	Tkinter	import	* #Pmw	not	needed	here! import	tkFileDialog class	PambukasNgPapeles(Frame):	… PambukasNgPapeles().mainloop()
def	__init__(self):	Frame.__init__(self)	self.master.geometry("200x100")	self.pack(expand=1,	fill=BOTH)	self.mahiwagangButones	=	Button(self,	text="Buksan	Now	Na",	command=self.buksan)	self.mahiwagangButones.pack() PYTHON GUI: FileDialog
PYTHON GUI: FileDialog Lugaw: 100 Chichiria: 40 Utang: 20 BentaNiBudoy.txt
def	__init__(self):	… def	buksan(self):	inputFile	=	tkFileDialog.askopenfile()	for	linya	in	inputFile:	mgaSalita	=	linya.split()	print	mgaSalita	inputFile.close() PYTHON GUI: FileDialog
def	__init__(self):	… def	buksan(self):	inputFile	=	tkFileDialog.askopenfile()	for	linya	in	inputFile:	mgaSalita	=	linya.split(“:”)	print	mgaSalita[0]	print	mgaSalita[1]	inputFile.close() PYTHON GUI: FileDialog (Remove Colon)
def	__init__(self):	… def	buksan(self):	inputFile	=	tkFileDialog.askopenfile()	for	linya	in	inputFile:	mgaSalita	=	linya.split(“:”)	for	salita	in	mgaSalita:	if	salita[-1]	==	“n”:	salita	=	salita[0:-1]	print	salita	inputFile.close() PYTHON GUI: FileDialog (Remove Newline)
def	__init__(self):	… def	buksan(self):	inputFile	=	tkFileDialog.askopenfile()	for	linya	in	inputFile:	mgaSalita	=	linya.split(“:”)	for	salita	in	mgaSalita:	if	salita[-1]	==	“n”:	salita	=	salita[0:-1]	print	salita,	inputFile.close() PYTHON GUI: FileDialog (Remove Newline)
PYTHON GUI: Closing Window
PYTHON GUI: Closing Window from	Tkinter	import	* import	tkMessageBox class	Panggunaw(Frame):	… Panggunaw().mainloop()
def	__init__(self):	Frame.__init__(self)	self.master.geometry("200x100")	self.pack(expand=1,	fill=BOTH)	self.gunawButones	=	Button(self,	text="Gunawin	and	mundo",	command=self.gunawin)	self.gunawButones.pack() PYTHON GUI: Closing Window
def	__init__(self):	… def	gunawin(self):	if	tkMessageBox.askokcancel("Gunawin	ang	Mundo", "Sigurado	po	kayo?"):	self.destroy() PYTHON GUI: Closing Window
PYTHON GUI: Canvas
PYTHON GUI: Canvas Coordinate System
PYTHON GUI: Canvas from	Tkinter	import	* class	MgaLinya(Frame):	… MgaLinya().mainloop()
def	__init__(self):	Frame.__init__(self)	self.master.geometry("200x300")	self.pack()	self.pader	=	Canvas(self)	self.pader.pack()	self.linyangPatayo	=	self.pader.create_line(	100,	0,	100,	200)	self.linyangPahiga	=	self.pader.create_line(	0,	100,	200,	100)	self.sentrongLetra	=	self.pader.create_text(	100,	100,	text="Sentro	ng	Mundo") PYTHON GUI: Canvas
def	__init__(self):	...	self.mahiwagangButones	=	Button(self,	text=	"Burahin	ang	nakasulat",	command=self.burahin)	self.mahiwagangButones.pack() def	burahin(self):	self.pader.delete(self.sentrongLetra) PYTHON GUI: Canvas
PYTHON GUI: Sine Curve
PYTHON GUI: Sine Curve #	plot	a	function	like	y	=	A*sin(x)	+	C from	Tkinter	import	* import	math class	SineCurve(Frame):	def	__init__(self):	... SineCurve().mainloop()
PYTHON GUI: Sine Curve def	__init__(self):	Frame.__init__(self)	self.pack()	width	=	400	height	=	300	sentro	=	height//2	self.c	=	Canvas(width=width,	height=height,	bg="white")	self.c.pack()
PYTHON GUI: Sine Curve def	__init__(self):	...	str1	=	"sin(x)=blue	cos(x)=red"	self.c.create_text(10,	20,	anchor=SW,	text=str1)	center_line	=	self.c.create_line(0,	sentro,	width,	sentro,	fill="green")	sin_line	=	self.c.create_line(self.curve(sentro,	flag="sine"),	fill="blue")	cos_line	=	self.c.create_line(self.curve(sentro,	flag="cosine"),	fill="red")
PYTHON GUI: Sine Curve def	curve(self,	sentro,	flag):	x_increment	=	1	x_factor	=	0.04	#	width	stretch	y_amplitude	=	80	#	height	stretch	xy	=	[]	for	x	in	range(400):	xy.append(x*x_increment)	#x	coordinates	#y	coordinates	if	flag	==	"sine":	xy.append(int(math.sin(x*x_factor)	*	y_amplitude)	+	sentro)	else:	xy.append(int(math.cos(x*x_factor)	*	y_amplitude)	+	sentro)	return	xy
PYTHON GUI: Circle Slider/Scale Widget
PYTHON GUI: Circle Slider/Scale Widget from	Tkinter	import	* class	CircleSlider(Frame):	def	__init__(self):	... CircleSlider().mainloop()
PYTHON GUI: Circle Slider/Scale Widget def	__init__(self):	Frame.__init__(self)	self.pack(expand=YES,	fill=BOTH)	self.master.geometry("460x420")	self.slider	=	Scale(self,	from_=0,	to=400,	orient=VERTICAL,	command=self.redraw_bilog)	self.slider.pack(side=LEFT,	fill=Y)	self.display	=	Canvas(self,	bg="gray")	self.display.pack(expand=YES,	fill=BOTH)
PYTHON GUI: Circle Slider/Scale Widget def	__init__(self):	... def	redraw_bilog(self,	current_cursor):	self.display.delete("bilog")	dulo	=	int(current_cursor)	self.display.create_oval(0,	0,	dulo,	dulo,	fill="green",	tags="bilog")
PYTHON GUI: Blinking Rectangle
PYTHON GUI: Blinking Rectangle from	Tkinter	import	* class	BlinkingRectangle(Frame):	def	__init__(self):	... BlinkingRectangle().mainloop()
PYTHON GUI: Blinking Rectangle def	__init__(self):	Frame.__init__(self)	self.pack()	self.canvas	=	Canvas(self,	height	=	100,	width	=	100)	self.canvas.pack()	self.rect	=	self.canvas.create_rectangle(25,	25,	75,	75,	fill	=	"red")	self.do_blink	=	False
PYTHON GUI: Blinking Rectangle def	__init__(self):	...	start_button	=	Button(self,	text="start	blinking",	command=self.start_blinking)	start_button.pack()	stop_button	=	Button(self,	text="stop	blinking",	command=self.stop_blinking)	stop_button.pack()
PYTHON GUI: Blinking Rectangle def	__init__(self):	... def	start_blinking(self):	self.do_blink	=	True	self.blink() def	stop_blinking(self):	self.do_blink	=	False
PYTHON GUI: Blinking Rectangle def	__init__(self):	... def	blink(self):	if	self.do_blink	==	True:	current_color	=	self.canvas.itemcget(self.rect,	"fill")	if	current_color	==	"red":	new_color	=	"blue"	else:	new_color	=	"red"	self.canvas.itemconfigure(self.rect,	fill=new_color)	self.after(1000,	self.blink)
REFERENCES q  Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001). q  Grayson - Python and Tkinter Programming (2000). q  Disclaimer: Most of the images/information used here have no proper source citation, and I do not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse and reintegrate materials that I think are useful or cool, then present them in another light, form, or perspective. Moreover, the images/information here are mainly used for illustration/educational purposes only, in the spirit of openness of data, spreading light, and empowering people with knowledge. J

Python Programming - XIII. GUI Programming