119
Engr. RANEL O. PADON XIII. GUI PROGRAMMING

Python Programming - XIII. GUI Programming

Embed Size (px)

Citation preview

Page 1: Python Programming - XIII. GUI Programming

Engr. RANEL O. PADON

XIII. GUI PROGRAMMING

Page 2: Python Programming - 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

Page 3: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Python

Operating

System

Page 4: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Python

Tcl

Tk

Operating

System

Page 5: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Python

Tcl

Tk

Operating

System

Tkinter

Page 6: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Tkinter

Operating

System

Page 7: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Tkinter = Tcl + Tk

Page 8: Python Programming - XIII. GUI Programming

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.

Page 9: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER = Tcl + Tk

Tcl: Tool Command Language

Interfacing with other Languages

Tcl/C++

Tcl/ Java

Page 10: Python Programming - XIII. GUI Programming

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.

Tcl/Tk

Tcl/Expect

Page 11: Python Programming - XIII. GUI Programming

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)

Page 12: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER = Tcl + Tk

Tk: ToolKit

created originally for Tcl

other language bindings also exist:

* Python/Tk = Tkinter

* Perl/Tk

* Ruby/Tk

Page 13: Python Programming - XIII. GUI Programming

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

Page 14: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Related Projects

Language Widget Toolkit

JavaAbstract Windowing Toolkit

Swing

PHPPHP - GTK

PHP - Qt

JavascriptjQuery UI

ExtJS

Python

Tkinter

Pyjamas

PyGTK

PyQt

PySide

wxPython

Page 15: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Related Projects ( Java’s Swing with Nimbus Theme)

Page 16: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER = Tcl + Tk

Page 17: Python Programming - XIII. GUI Programming

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.

Page 18: Python Programming - XIII. GUI Programming

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.

Page 19: Python Programming - XIII. GUI Programming

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).

Page 20: Python Programming - XIII. GUI Programming

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.

Page 21: Python Programming - XIII. GUI Programming

PYTHON GUI: Pros

Maturity

First released in 1990, the core is well developed and stable.

Page 22: Python Programming - XIII. GUI Programming

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.

Page 23: Python Programming - XIII. GUI Programming

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.

Page 24: Python Programming - XIII. GUI Programming

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.

Page 25: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Python Widget ( Window Gadget) Subclasses

Page 26: Python Programming - XIII. GUI Programming

PYTHON GUI: TKINTER

Python Widgets

Page 27: Python Programming - XIII. GUI Programming

from Tkinter import *

Frame().mainloop()

PYTHON GUI: Frame

Page 28: Python Programming - XIII. GUI Programming

from Tkinter import *

class GuiTest(Frame):def __init__(self):

Frame.__init__(self)self.pack()

GuiTest().mainloop()

PYTHON GUI: Frame

Page 29: Python Programming - XIII. GUI Programming

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

Page 30: Python Programming - XIII. GUI Programming

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

Page 31: Python Programming - XIII. GUI Programming

from Tkinter import *

class GuiTest(Frame):def __init__(self):

self.text = Entry(self, name = “butas”)self.text.pack()

GuiTest().mainloop()

PYTHON GUI: Entry

Page 32: Python Programming - XIII. GUI Programming

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

Page 33: Python Programming - XIII. GUI Programming

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

Page 34: Python Programming - XIII. GUI Programming

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

Page 35: Python Programming - XIII. GUI Programming

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

Page 36: Python Programming - XIII. GUI Programming

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

Page 37: Python Programming - XIII. GUI Programming

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

Page 38: Python Programming - XIII. GUI Programming

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

Page 39: Python Programming - XIII. GUI Programming

PYTHON GUI: Radiobutton

Page 40: Python Programming - XIII. GUI Programming

PYTHON GUI: Radiobutton

from Tkinter import *

class ChannelButton(Frame):…

ChannelButton().mainloop()

Page 41: Python Programming - XIII. GUI Programming

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

Page 42: Python Programming - XIII. GUI Programming

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

Page 43: Python Programming - XIII. GUI Programming

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

Page 44: Python Programming - XIII. GUI Programming

PYTHON GUI: Checkbutton

Page 45: Python Programming - XIII. GUI Programming

from Tkinter import *

class CheckbuttonTest(Frame):…

CheckbuttonTest().mainloop()

PYTHON GUI: Radiobutton

Page 46: Python Programming - XIII. GUI Programming

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

Page 47: Python Programming - XIII. GUI Programming

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

Page 48: Python Programming - XIII. GUI Programming

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

Page 49: Python Programming - XIII. GUI Programming

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

Page 50: Python Programming - XIII. GUI Programming

PYTHON GUI: Checkbutton

Page 51: Python Programming - XIII. GUI Programming

from Tkinter import *

class TikbalangCheckbutton(Frame):…

TikbalangCheckbutton().mainloop()

PYTHON GUI: Radiobutton

Page 52: Python Programming - XIII. GUI Programming

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

Page 53: Python Programming - XIII. GUI Programming

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

Page 54: Python Programming - XIII. GUI Programming

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

Page 55: Python Programming - XIII. GUI Programming

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

Page 56: Python Programming - XIII. GUI Programming

PYTHON GUI: Grid Layout

Page 57: Python Programming - XIII. GUI Programming
Page 58: Python Programming - XIII. GUI Programming

from Tkinter import *

class PinasGrid(Frame):…

PinasGrid().mainloop()

PYTHON GUI: Grid Layout

Page 59: Python Programming - XIII. GUI Programming

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

Page 60: Python Programming - XIII. GUI Programming

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

Page 61: Python Programming - XIII. GUI Programming

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

Page 62: Python Programming - XIII. GUI Programming

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

Page 63: Python Programming - XIII. GUI Programming

PYTHON GUI: Calculator

Page 64: Python Programming - XIII. GUI Programming

PYTHON GUI: Calculator

Page 65: Python Programming - XIII. GUI Programming

PYTHON GUI: Calculator

Page 66: Python Programming - XIII. GUI Programming

PYTHON GUI: Calculator

Page 67: Python Programming - XIII. GUI Programming

from __future__ import divisionfrom Tkinter import *

class CalcuNiRanie(Frame):…

CalcuNiRanie().mainloop()

PYTHON GUI: Calculator

Page 68: Python Programming - XIII. GUI Programming

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

Page 69: Python Programming - XIII. GUI Programming

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

Page 70: Python Programming - XIII. GUI Programming

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

Page 71: Python Programming - XIII. GUI Programming

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

Page 72: Python Programming - XIII. GUI Programming

use the eval() function for evaluating arithmetic operations

involving string parameters containing numbers

>>print eval("3 + 4")

#prints the answer: 7

PYTHON GUI: Calculator

Page 73: Python Programming - XIII. GUI Programming

Python Mega Widgets (Pmw)

toolkit that provides high-level GUI components from the

combinations of Tkinter widgets

* Menubar, ScrolledText, etc.

PYTHON GUI: Pmw

Page 74: Python Programming - XIII. GUI Programming

Download Pmw and extract the contents of src folder to a folder

e.g. extract to: C:\Pyhon27\src

PYTHON GUI: Pmw

Run the setup.py executable file in Command Prompt

(install is a command-line parameter of setup.py ):

Page 75: Python Programming - XIII. GUI Programming

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

Page 76: Python Programming - XIII. GUI Programming

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

Page 77: Python Programming - XIII. GUI Programming

PYTHON GUI: Pmw.ScrolledText

Page 78: Python Programming - XIII. GUI Programming

PYTHON GUI: Pmw.ScrolledText

from Tkinter import *import Pmw

class LakasNgScrolledText(Frame):…

LakasNgScrolledText().mainloop()

Page 79: Python Programming - XIII. GUI Programming

def __init__(self):Frame.__init__(self)Pmw.initialise()self.packself.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!

Page 80: Python Programming - XIII. GUI Programming

def __init__(self): …

def iTeleport(self, propeta):lamanNgButas = propeta.widget.get()

self.dingding.settext(self.dingding.get() + \lamanNgButas)

self.butas.delete(0, END)

self.dingding.insert(END, lamanNgButas + "\n")

PYTHON GUI: Pmw.ScrolledText

Page 81: Python Programming - XIII. GUI Programming

PYTHON GUI: Pmw.Menubar

Page 82: Python Programming - XIII. GUI Programming

PYTHON GUI: Pmw.Menubar

from Tkinter import *import Pmwimport tkMessageBox

class TindahanNiBudoy (Frame):…

TindahanNiBudoy().mainloop()

Page 83: Python Programming - XIII. GUI Programming

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

Page 84: Python Programming - XIII. GUI Programming

def __init__(self):…

self.mayBoyBawang = BooleanVar()

self.sabitanNgPaninda.addmenuitem("Chichiria",\"checkbutton", label = "Boy Bawang",\command = self.idagdagAngBoyBawang,\variable = self.mayBoyBawang)

PYTHON GUI: Pmw.Menubar

Page 85: Python Programming - XIII. GUI Programming

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

Page 86: Python Programming - XIII. GUI Programming

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

Page 87: Python Programming - XIII. GUI Programming

PYTHON GUI: FileDialog

Page 88: Python Programming - XIII. GUI Programming

PYTHON GUI: FileDialog

from Tkinter import *#Pmw not needed here!import tkFileDialog

class PambukasNgPapeles(Frame):…

PambukasNgPapeles().mainloop()

Page 89: Python Programming - XIII. GUI Programming

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

Page 90: Python Programming - XIII. GUI Programming

PYTHON GUI: FileDialog

Lugaw: 100

Chichiria: 40

Utang: 20

BentaNiBudoy.txt

Page 91: Python Programming - XIII. GUI Programming

def __init__(self):…

def buksan(self):inputFile = tkFileDialog.askopenfile()

for linya in inputFile:mgaSalita = linya.split()

print mgaSalita

inputFile.close()

PYTHON GUI: FileDialog

Page 92: Python Programming - XIII. GUI Programming

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)

Page 93: Python Programming - XIII. GUI Programming

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)

Page 94: Python Programming - XIII. GUI Programming

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)

Page 95: Python Programming - XIII. GUI Programming

PYTHON GUI: Closing Window

Page 96: Python Programming - XIII. GUI Programming

PYTHON GUI: Closing Window

from Tkinter import *import tkMessageBox

class Panggunaw(Frame):…

Panggunaw().mainloop()

Page 97: Python Programming - XIII. GUI Programming

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

Page 98: Python Programming - XIII. GUI Programming

def __init__(self):…

def gunawin(self):if tkMessageBox.askokcancel("Gunawin ang Mundo",\

"Sigurado po kayo?"):self.destroy()

PYTHON GUI: Closing Window

Page 99: Python Programming - XIII. GUI Programming

PYTHON GUI: Canvas

Page 100: Python Programming - XIII. GUI Programming

PYTHON GUI: Canvas Coordinate System

Page 101: Python Programming - XIII. GUI Programming

PYTHON GUI: Canvas

from Tkinter import *

class MgaLinya(Frame):…

MgaLinya().mainloop()

Page 102: Python Programming - XIII. GUI Programming

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

Page 103: Python Programming - XIII. GUI Programming

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

Page 104: Python Programming - XIII. GUI Programming

PYTHON GUI: Sine Curve

Page 105: Python Programming - XIII. GUI Programming

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()

Page 106: Python Programming - XIII. GUI Programming

PYTHON GUI: Sine Curve

def __init__(self):Frame.__init__(self)self.pack()

width = 400height = 300sentro = height//2

self.c = Canvas(width=width, height=height,\bg="white")

self.c.pack()

Page 107: Python Programming - XIII. GUI Programming

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")

Page 108: Python Programming - XIII. GUI Programming

PYTHON GUI: Sine Curve

def curve(self, sentro, flag):x_increment = 1x_factor = 0.04 # width stretchy_amplitude = 80 # height stretch

xy = []for x in range(400):

xy.append(x*x_increment) #x coordinates

#y coordinatesif 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

Page 109: Python Programming - XIII. GUI Programming

PYTHON GUI: Circle Slider/Scale Widget

Page 110: Python Programming - XIII. GUI Programming

PYTHON GUI: Circle Slider/Scale Widget

from Tkinter import *

class CircleSlider(Frame):def __init__(self):

...

CircleSlider().mainloop()

Page 111: Python Programming - XIII. GUI Programming

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)

Page 112: Python Programming - XIII. GUI Programming

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")

Page 113: Python Programming - XIII. GUI Programming

PYTHON GUI: Blinking Rectangle

Page 114: Python Programming - XIII. GUI Programming

PYTHON GUI: Blinking Rectangle

from Tkinter import *

class BlinkingRectangle(Frame):def __init__(self):

...

BlinkingRectangle().mainloop()

Page 115: Python Programming - XIII. GUI Programming

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

Page 116: Python Programming - XIII. GUI Programming

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()

Page 117: Python Programming - XIII. GUI Programming

PYTHON GUI: Blinking Rectangle

def __init__(self):...

def start_blinking(self):self.do_blink = Trueself.blink()

def stop_blinking(self):self.do_blink = False

Page 118: Python Programming - XIII. GUI Programming

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)

Page 119: Python Programming - XIII. GUI Programming

REFERENCES

Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).

Grayson - Python and Tkinter Programming (2000).

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.