Engr. RANEL O. PADON
XIII. GUI PROGRAMMING
PYTHON PROGRAMMING TOPICS
I
•Introduction to Python Programming
II
•Python Basics
III
•Controlling the Program Flow
IV
•Pr...
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, networki...
PYTHON GUI: TKINTER = Tcl + Tk
Tcl: Tool Command Language
Interfacing with other Languages
 Tcl/C++
 Tcl/Java
PYTHON GUI: TKINTER = Tcl + Tk
Tcl: Tool Command Language
allows extension packages, which provide additional functionalit...
PYTHON GUI: TKINTER = Tcl + Tk
Tk: ToolKit
open-source, cross platform widget toolkit for building GUI
other common widget...
PYTHON GUI: TKINTER = Tcl + Tk
Tk: ToolKit
created originally for Tcl
other language bindings also exist:
* Python/Tk = Tk...
PYTHON GUI: TKINTER = Tcl + Tk
Tkinter: Tk Interface
* wrapper for Tcl to access Tk
* Python and Tcl could co-exist in a P...
PYTHON GUI: TKINTER
Related Projects
Language Widget Toolkit
Java
Abstract Windowing Toolkit
Swing
PHP
PHP - GTK
PHP - Qt
...
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 ...
PYTHON GUI: TKINTER
Widget
A user interface element
(text box, combo box, or top-level window).
On Windows, the common ter...
PYTHON GUI: Pros
Brevity
Python programs using Tkinter can be very brief, partly because
of the power of Python, but also ...
PYTHON GUI: Pros
Cross platform
Tk provides widgets on Windows, Macs, and most Unix
implementations with very little platf...
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 exte...
PYTHON GUI: Cons
Speed
Most calls to Tkinter are formatted as a Tcl command
(a string) and interpreted by Tcl from where t...
PYTHON GUI: Cons
Tcl
Python purists often balk at the need to install another
scripting language in order to perform GUI t...
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()
PYTH...
from Tkinter import *
class GuiTest(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.master.title("Ranel'...
from Tkinter import *
class GuiTest(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.master.title("Ranel'...
from Tkinter import *
class GuiTest(Frame):
def __init__(self):
…
self.text = Entry(self, name = “butas”)
self.text.pack()...
from Tkinter import *
class GuiTest(Frame):
def __init__(self):
…
self.text = Entry(self, name = “butas”)
self.text.bind("...
from Tkinter import *
from tkMessageBox import *
class GuiTest(Frame):
def __init__(self):
…
self.text = Entry(self, name ...
from Tkinter import *
from tkMessageBox import *
class GuiTest(Frame):
def __init__(self):
…
self.text = Entry(self, name ...
from Tkinter import *
from tkMessageBox import *
class GuiTest(Frame):
def __init__(self):
…
self.text = Entry(self, name ...
from Tkinter import *
from tkMessageBox import *
class GuiTest(Frame):
def __init__(self):
…
self.button = Button(self, te...
from Tkinter import *
class GuiTest(Frame):
def __init__(self):
…
self.button = Button(self, text = "Koya wag po!",
comman...
class GuiTest(Frame):
def __init__(self):
…
self.imageGoogle = PhotoImage(file = "google.gif")
self.buttonPic = Button(sel...
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(ex...
def __init__(self):
…
listahanNgChannels = ["GMA","ABS-CBN","TV-5","DZUP"]
self.napilingChannel = StringVar()
self.napilin...
def __init__(self):
…
def ipakitaAngNapili(self):
print self.napilingChannel.get()
if self.napilingChannel.get() == "GMA":...
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(expa...
def __init__(self):
…
self.makapalBa = BooleanVar()
self.tsekbaksMakapal = Checkbutton(self, text = 
“Pakapalin”, variable...
def __init__(self):
…
self.tagilidBa = BooleanVar()
self.tsekbaksTagilid = Checkbutton(self, text = 
"Itagilid", variable ...
def __init__(self):
…
def baguhinAngFont(self):
hitsuraNgLaman = "Arial 10"
if self.makapalBa.get():
hitsuraNgLaman += " b...
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")
se...
def __init__(self):
…
self.taoBa = BooleanVar()
self.tsekbaksTao = Checkbutton(self, text = "Tao",
variable = self.taoBa,
...
def __init__(self):
…
self.kabayoBa = BooleanVar()
self.tsekbaksKabayo = Checkbutton(self,
text = "Kabayo",
variable = sel...
def baguhinAngLaman(self):
if self.taoBa.get() and self.kabayoBa.get():
self.laman.delete(0, END)
self.laman.insert(INSERT...
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(e...
def __init__(self):
…
self.sentro = Label(self, text="Tayo na sa Pinas!",
foreground="blue")
self.sentro.grid(row=1, colum...
def __init__(self):
…
self.columnconfigure(0, weight = 1)
self.columnconfigure(1, weight = 1)
self.columnconfigure(2, weig...
def __init__(self):
…
def pumuntaSaHilaga(self):
self.sentro.config(text = "Tayo na sa Batanes!")
def pumuntaSaKanluran(se...
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: C...
def __init__(self):
Frame.__init__(self)
self.master.title("Calcu ni Kuya Ranie")
self.master.geometry("250x250")
self.pac...
def __init__(self):
…
self.frame2 = Frame(self)
self.frame2.pack(expand=1, fill=BOTH)
self.pito = Button(self.frame2, text...
def __init__(self):
…
self.frame2.columnconfigure(0, weight = 1)
self.frame2.columnconfigure(1, weight = 1)
self.frame2.co...
def __init__(self):
…
def pito(self):
self.screen.insert(END,'7')
def walo(self):
self.screen.insert(END,'8')
…
def anoAng...
use the eval() function for evaluating arithmetic operations
involving string parameters containing numbers
>>print eval("...
Python Mega Widgets (Pmw)
toolkit that provides high-level GUI components from the
combinations of Tkinter widgets
* Menub...
Download Pmw and extract the contents of src folder to a folder
e.g. extract to: C:Pyhon27src
PYTHON GUI: Pmw
Run the setu...
It means it could not find a python.exe file to run setup.py,
hence you must add the Path of python interpreter/executable...
Detailed Step for Adding Python to Environment Variables:
right-click Computer > Properties > Advanced System Settings
> A...
PYTHON GUI: Pmw.ScrolledText
PYTHON GUI: Pmw.ScrolledText
from Tkinter import *
import Pmw
class LakasNgScrolledText(Frame):
…
LakasNgScrolledText().ma...
def __init__(self):
Frame.__init__(self)
Pmw.initialise()
self.pack
self.master.geometry("150x100")
self.butas = Entry(sel...
def __init__(self):
…
def iTeleport(self, propeta):
lamanNgButas = propeta.widget.get()
self.dingding.settext(self.dingdin...
PYTHON GUI: Pmw.Menubar
PYTHON GUI: Pmw.Menubar
from Tkinter import *
import Pmw
import tkMessageBox
class TindahanNiBudoy (Frame):
…
TindahanNiBu...
def __init__(self):
Frame.__init__(self)
Pmw.initialise()
self.master.geometry("300x200")
self.pack(expand=1, fill=BOTH)
s...
def __init__(self):
…
self.mayBoyBawang = BooleanVar()
self.sabitanNgPaninda.addmenuitem("Chichiria",
"checkbutton", label...
def __init__(self):
…
def initinAngLugaw(self):
tkMessageBox.showinfo(None,
"Unlimited Lugaw for P20!")
def idagdagAngBoyB...
PYTHON GUI: Other Tk functionalities
1. File Dialog for file handling
2. Closing inner and main windows
3. Drawing on Canv...
PYTHON GUI: FileDialog
PYTHON GUI: FileDialog
from Tkinter import *
#Pmw not needed here!
import tkFileDialog
class PambukasNgPapeles(Frame):
…
P...
def __init__(self):
Frame.__init__(self)
self.master.geometry("200x100")
self.pack(expand=1, fill=BOTH)
self.mahiwagangBut...
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.s...
def __init__(self):
…
def buksan(self):
inputFile = tkFileDialog.askopenfile()
for linya in inputFile:
mgaSalita = linya.s...
def __init__(self):
…
def buksan(self):
inputFile = tkFileDialog.askopenfile()
for linya in inputFile:
mgaSalita = linya.s...
def __init__(self):
…
def buksan(self):
inputFile = tkFileDialog.askopenfile()
for linya in inputFile:
mgaSalita = linya.s...
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 ...
def __init__(self):
…
def gunawin(self):
if tkMessageBox.askokcancel("Gunawin ang Mundo",
"Sigurado po kayo?"):
self.destr...
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....
def __init__(self):
...
self.mahiwagangButones = Button(self, 
text= "Burahin ang nakasulat",
command=self.burahin)
self.m...
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):
d...
PYTHON GUI: Sine Curve
def __init__(self):
Frame.__init__(self)
self.pack()
width = 400
height = 300
sentro = height//2
se...
PYTHON GUI: Sine Curve
def __init__(self):
...
str1 = "sin(x)=blue cos(x)=red"
self.c.create_text(10, 20, anchor=SW, text=...
PYTHON GUI: Sine Curve
def curve(self, sentro, flag):
x_increment = 1
x_factor = 0.04 # width stretch
y_amplitude = 80 # h...
PYTHON GUI: Circle Slider/Scale Widget
PYTHON GUI: Circle Slider/Scale Widget
from Tkinter import *
class CircleSlider(Frame):
def __init__(self):
...
CircleSlid...
PYTHON GUI: Circle Slider/Scale Widget
def __init__(self):
Frame.__init__(self)
self.pack(expand=YES, fill=BOTH)
self.mast...
PYTHON GUI: Circle Slider/Scale Widget
def __init__(self):
...
def redraw_bilog(self, current_cursor):
self.display.delete...
PYTHON GUI: Blinking Rectangle
PYTHON GUI: Blinking Rectangle
from Tkinter import *
class BlinkingRectangle(Frame):
def __init__(self):
...
BlinkingRecta...
PYTHON GUI: Blinking Rectangle
def __init__(self):
Frame.__init__(self)
self.pack()
self.canvas = Canvas(self, height = 10...
PYTHON GUI: Blinking Rectangle
def __init__(self):
...
start_button = Button(self, text="start blinking",
command=self.sta...
PYTHON GUI: Blinking Rectangle
def __init__(self):
...
def start_blinking(self):
self.do_blink = True
self.blink()
def sto...
PYTHON GUI: Blinking Rectangle
def __init__(self):
...
def blink(self):
if self.do_blink == True:
current_color = self.can...
REFERENCES
 Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).
 Grayson - Python and Tkinter Progra...
Python Programming - XIII. GUI Programming
Upcoming SlideShare
Loading in...5
×

Python Programming - XIII. GUI Programming

2,704

Published on

Published in: Technology
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,704
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
257
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

Python Programming - XIII. GUI Programming

  1. 1. Engr. RANEL O. PADON XIII. GUI PROGRAMMING
  2. 2. 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
  3. 3. PYTHON GUI: TKINTER Python Operating System
  4. 4. PYTHON GUI: TKINTER Python Tcl Tk Operating System
  5. 5. PYTHON GUI: TKINTER Python Tcl Tk Operating System Tkinter
  6. 6. PYTHON GUI: TKINTER Tkinter Operating System
  7. 7. PYTHON GUI: TKINTER Tkinter = Tcl + Tk
  8. 8. 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.
  9. 9. PYTHON GUI: TKINTER = Tcl + Tk Tcl: Tool Command Language Interfacing with other Languages  Tcl/C++  Tcl/Java
  10. 10. 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
  11. 11. 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)
  12. 12. PYTHON GUI: TKINTER = Tcl + Tk Tk: ToolKit created originally for Tcl other language bindings also exist: * Python/Tk = Tkinter * Perl/Tk * Ruby/Tk
  13. 13. 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
  14. 14. 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
  15. 15. PYTHON GUI: TKINTER Related Projects (Java’s Swing with Nimbus Theme)
  16. 16. PYTHON GUI: TKINTER = Tcl + Tk
  17. 17. 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.
  18. 18. 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.
  19. 19. 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).
  20. 20. 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.
  21. 21. PYTHON GUI: Pros Maturity First released in 1990, the core is well developed and stable.
  22. 22. 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.
  23. 23. 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.
  24. 24. 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.
  25. 25. PYTHON GUI: TKINTER Python Widget (Window Gadget) Subclasses
  26. 26. PYTHON GUI: TKINTER Python Widgets
  27. 27. from Tkinter import * Frame().mainloop() PYTHON GUI: Frame
  28. 28. from Tkinter import * class GuiTest(Frame): def __init__(self): Frame.__init__(self) self.pack() GuiTest().mainloop() PYTHON GUI: Frame
  29. 29. 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
  30. 30. 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
  31. 31. from Tkinter import * class GuiTest(Frame): def __init__(self): … self.text = Entry(self, name = “butas”) self.text.pack() GuiTest().mainloop() PYTHON GUI: Entry
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 36. 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
  37. 37. 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
  38. 38. 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
  39. 39. PYTHON GUI: Radiobutton
  40. 40. PYTHON GUI: Radiobutton from Tkinter import * class ChannelButton(Frame): … ChannelButton().mainloop()
  41. 41. 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
  42. 42. 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
  43. 43. 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
  44. 44. PYTHON GUI: Checkbutton
  45. 45. from Tkinter import * class CheckbuttonTest(Frame): … CheckbuttonTest().mainloop() PYTHON GUI: Radiobutton
  46. 46. 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
  47. 47. 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
  48. 48. 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
  49. 49. 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
  50. 50. PYTHON GUI: Checkbutton
  51. 51. from Tkinter import * class TikbalangCheckbutton(Frame): … TikbalangCheckbutton().mainloop() PYTHON GUI: Radiobutton
  52. 52. 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
  53. 53. 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
  54. 54. 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
  55. 55. 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
  56. 56. PYTHON GUI: Grid Layout
  57. 57. from Tkinter import * class PinasGrid(Frame): … PinasGrid().mainloop() PYTHON GUI: Grid Layout
  58. 58. 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
  59. 59. 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
  60. 60. 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
  61. 61. 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
  62. 62. PYTHON GUI: Calculator
  63. 63. PYTHON GUI: Calculator
  64. 64. PYTHON GUI: Calculator
  65. 65. PYTHON GUI: Calculator
  66. 66. from __future__ import division from Tkinter import * class CalcuNiRanie(Frame): … CalcuNiRanie().mainloop() PYTHON GUI: Calculator
  67. 67. 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
  68. 68. 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
  69. 69. 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
  70. 70. 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
  71. 71. use the eval() function for evaluating arithmetic operations involving string parameters containing numbers >>print eval("3 + 4") #prints the answer: 7 PYTHON GUI: Calculator
  72. 72. Python Mega Widgets (Pmw) toolkit that provides high-level GUI components from the combinations of Tkinter widgets * Menubar, ScrolledText, etc. PYTHON GUI: Pmw
  73. 73. 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 ):
  74. 74. 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
  75. 75. 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
  76. 76. PYTHON GUI: Pmw.ScrolledText
  77. 77. PYTHON GUI: Pmw.ScrolledText from Tkinter import * import Pmw class LakasNgScrolledText(Frame): … LakasNgScrolledText().mainloop()
  78. 78. 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!
  79. 79. 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
  80. 80. PYTHON GUI: Pmw.Menubar
  81. 81. PYTHON GUI: Pmw.Menubar from Tkinter import * import Pmw import tkMessageBox class TindahanNiBudoy (Frame): … TindahanNiBudoy().mainloop()
  82. 82. 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
  83. 83. def __init__(self): … self.mayBoyBawang = BooleanVar() self.sabitanNgPaninda.addmenuitem("Chichiria", "checkbutton", label = "Boy Bawang", command = self.idagdagAngBoyBawang, variable = self.mayBoyBawang) PYTHON GUI: Pmw.Menubar
  84. 84. 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
  85. 85. 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
  86. 86. PYTHON GUI: FileDialog
  87. 87. PYTHON GUI: FileDialog from Tkinter import * #Pmw not needed here! import tkFileDialog class PambukasNgPapeles(Frame): … PambukasNgPapeles().mainloop()
  88. 88. 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
  89. 89. PYTHON GUI: FileDialog Lugaw: 100 Chichiria: 40 Utang: 20 BentaNiBudoy.txt
  90. 90. def __init__(self): … def buksan(self): inputFile = tkFileDialog.askopenfile() for linya in inputFile: mgaSalita = linya.split() print mgaSalita inputFile.close() PYTHON GUI: FileDialog
  91. 91. 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)
  92. 92. 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)
  93. 93. 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)
  94. 94. PYTHON GUI: Closing Window
  95. 95. PYTHON GUI: Closing Window from Tkinter import * import tkMessageBox class Panggunaw(Frame): … Panggunaw().mainloop()
  96. 96. 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
  97. 97. def __init__(self): … def gunawin(self): if tkMessageBox.askokcancel("Gunawin ang Mundo", "Sigurado po kayo?"): self.destroy() PYTHON GUI: Closing Window
  98. 98. PYTHON GUI: Canvas
  99. 99. PYTHON GUI: Canvas Coordinate System
  100. 100. PYTHON GUI: Canvas from Tkinter import * class MgaLinya(Frame): … MgaLinya().mainloop()
  101. 101. 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
  102. 102. 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
  103. 103. PYTHON GUI: Sine Curve
  104. 104. 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()
  105. 105. 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()
  106. 106. 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")
  107. 107. 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
  108. 108. PYTHON GUI: Circle Slider/Scale Widget
  109. 109. PYTHON GUI: Circle Slider/Scale Widget from Tkinter import * class CircleSlider(Frame): def __init__(self): ... CircleSlider().mainloop()
  110. 110. 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)
  111. 111. 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")
  112. 112. PYTHON GUI: Blinking Rectangle
  113. 113. PYTHON GUI: Blinking Rectangle from Tkinter import * class BlinkingRectangle(Frame): def __init__(self): ... BlinkingRectangle().mainloop()
  114. 114. 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
  115. 115. 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()
  116. 116. 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
  117. 117. 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)
  118. 118. 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. 
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×