SlideShare una empresa de Scribd logo
1 de 96
Descargar para leer sin conexión
Tkinter doesn’t suck!
                               Honest!




Saturday, 7 November 2009
“What GUI toolkit
                              should I use?”

                                 – random poster in random forum
Saturday, 7 November 2009
wxWindows!



Saturday, 7 November 2009
import wx

      class Application(wx.Frame):
          def __init__(self, parent):
              wx.Frame.__init__(self, parent, -1, 'My GUI', size=(300, 200))
              panel = wx.Panel(self)
              sizer = wx.BoxSizer(wx.VERTICAL)
              panel.SetSizer(sizer)
              txt = wx.StaticText(panel, -1, 'Hello, world')
              sizer.Add(txt, 0, wx.TOP|wx.LEFT, 20)
              self.Centre()
              self.Show(True)

      app = wx.App(0)
      Application(None)
      app.MainLoop()




Saturday, 7 November 2009
pyGTK



Saturday, 7 November 2009
import gtk

                            window = gtk.Window()
                            label = gtk.Label("Hello, world")
                            window.add(label)
                            window.show_all()
                            gtk.main()




Saturday, 7 November 2009
PyQt!



Saturday, 7 November 2009
import sys
                            import PyQt4.Qt as qt

                            a=qt.QApplication(sys.argv)
                            w=qt.QLabel("Hello, world")
                            w.show()
                            a.exec_()




Saturday, 7 November 2009
“whatever you do...



Saturday, 7 November 2009
...don’t use Tkinter!”



Saturday, 7 November 2009
“Tkinter sucks!”



Saturday, 7 November 2009
import Tkinter as tk

                            root = tk.Tk()
                            tk.Label(root, text="Hello, world").pack()
                            root.mainloop()




Saturday, 7 November 2009
“yeah, OMG, Tkinter
                                   sucks!”


Saturday, 7 November 2009
I disagree



Saturday, 7 November 2009
1. it’s simple to use
                                               - rich base widget set
                                               - which is not verbose
                                               - automatic packing




Saturday, 7 November 2009
2. it’s always there

                                               on Windows & OS X

                                               -- on Linuxes you might
                                               need to install an
                                               optional package




Saturday, 7 November 2009
3. it’s mature

                                         first release 1991
                                         8.0 released August 1999
                                         8.5 released December 2007




Saturday, 7 November 2009
how I discovered this
                               I had this project that I wanted to be click-to-run, but needed to select a file

                               Looked for a cross-platform “file dialog” solution and found some hacks

                               Then I noticed a reference to Tkinter, and lo and behold...




Saturday, 7 November 2009
filename = tkFileDialog.askopenfilename(parent=root,
                         filetypes=[('ReStructuredText Files', '.rst .txt'),
                                    ('All Files', '.*')],
                         title='Select your presentation file')




Saturday, 7 November 2009
Saturday, 7 November 2009
well, if it can do that...

                                     what about the program’s command-line options?




Saturday, 7 November 2009
Saturday, 7 November 2009
self.root = tk.Tk()
   frame = Tk.Frame(self.root)
   frame.pack()

   Tk.Label(frame, text='Bruce, the Presentation Tool!').pack()

   self.fullscreen = Tk.IntVar()
   Tk.Checkbutton(frame, text='Fullscreen?', variable=self.fullscreen).pack()

   # screen selection
   display = pyglet.window.get_platform().get_default_display()
   N = len(display.get_screens())
   self.screen = Tk.IntVar(0)
   if N > 1:
       for n in range(N):
           Tk.Radiobutton(frame, text="Display on screen %d"%(n+1),
               variable=self.screen, value=n).pack()

   self.timer = Tk.IntVar()
   Tk.Checkbutton(frame, text='Show Timer?', variable=self.timer).pack()
   self.page_count = Tk.IntVar()
   Tk.Checkbutton(frame, text='Show Page Count?', variable=self.page_count).pack()
   self.bullet_mode = Tk.IntVar()
   Tk.Checkbutton(frame, text='Run in Bullet Mode?', variable=self.bullet_mode).pack()
   self.source = Tk.IntVar()
   Tk.Checkbutton(frame, text='Display source in console?', variable=self.source).pack()

   Tk.Button(frame, text='Play Presentation', command=self.go).pack()

Saturday, 7 November 2009
specific Tkinter gripes



Saturday, 7 November 2009
1. it’s not pretty



Saturday, 7 November 2009
1. it’s not pretty
                             1. it doesn’t look native,
                             2. fonts are not anti-aliased



Saturday, 7 November 2009
2. extending is tricky



Saturday, 7 November 2009
native look and feel
                                 (since Tk 8.0, 1999)




Saturday, 7 November 2009
native look and feel
                                   (since Tk 8.0, 1999)
                             (much improved in Tk 8.5, 2008)



Saturday, 7 November 2009
native look and feel
                                   (since Tk 8.0, 1999)
                             (much improved in Tk 8.5, 2008)
                               (“less ugly but not perfect”)

Saturday, 7 November 2009
Saturday, 7 November 2009
Saturday, 7 November 2009
truetype / opentype
                                   fonts
                                  (since Tk 8.5)




Saturday, 7 November 2009
1. Simple to use



Saturday, 7 November 2009
Widgets



Saturday, 7 November 2009
import Tkinter as tk

                            root = tk.Tk()
                            tk.Label(root, text="Hello, world").pack()
                            root.mainloop()




                                                                         demo image display

                                                                         label properties:
                                                                         foreground, background,
                                                                         font, ???




Saturday, 7 November 2009
import Tkinter as tk

                            root = tk.Tk()
                            tk.Label(root, text="Hello, world").pack()
                            root.mainloop()




                                                                         No point showing the
                                                                         other three lines in other
                                                                         examples




Saturday, 7 November 2009
from PIL import Image, ImageTk
                            image = ImageTk.PhotoImage(Image.open('kitten.jpg'))
                            tk.Label(root, image=image).pack()




Saturday, 7 November 2009
def pressed():
                                print 'You pressed me!'

                            tk.Button(root, text='Press me!',
                                command=pressed).pack()




Saturday, 7 November 2009
entry = tk.Entry(root)
                            entry.pack()
                            entry.insert(0, 'some text')




Saturday, 7 November 2009
value = tk.IntVar()
                            tk.Checkbutton(root, text='Checked?',
                                    variable=value).pack()




Saturday, 7 November 2009
value = tk.IntVar()
                            for n in range(4):
                                tk.Radiobutton(root, value=n
                                    text="Selection %d"%(n+1),
                                    variable=value).pack()




Saturday, 7 November 2009
value = tk.StringVar(value='One')
                            tk.OptionMenu(root, value, 'One', 'Two',
                                'Three').pack()




                                                                       10 minutes




Saturday, 7 November 2009
listbox = tk.Listbox(root)
                            listbox.pack()
                            listbox.insert(tk.END, "a list entry")
                            for item in ‘one two three four’.split():
                                listbox.insert(tk.END, item)




Saturday, 7 November 2009
text = tk.Text(root)
                            text.pack()
                            text.insert(tk.END, '''some text
                            more text''')




                                                               also allows:
                                                               - embedding of images
                                                               and widgets
                                                               - searching
                                                               - tagging (identification,
                                                               useful for properties)
                                                               - styles




Saturday, 7 November 2009
scale = tk.Scale(root, from_=0, to=100)
                            scale.pack()




Saturday, 7 November 2009
w = tk.Canvas(root, width=200, height=100)
                            w.pack()
                            w.create_line(0, 0, 200, 100)
                            w.create_line(0, 100, 200, 0,
                                fill="red", dash=(4, 4))
                            w.create_rectangle(50, 25, 150, 75,
                                fill="blue")




                                                                         - line (with arrows), arc,
                                                                         image, oval, polygon,
                                                                         rectangle, text, widgets
                                                                         - outline, fill
                                                                         - scrollable (limitable)
                                                                         - picking (with closest)




Saturday, 7 November 2009
1. Simple to use



Saturday, 7 November 2009
Packing



Saturday, 7 November 2009
rows or columns
                                              the pack manager packs
                                              into rows or columns

                                              the default is column,
                                              centered.




Saturday, 7 November 2009
in the beginning there is
                            a container, and it is
                            empty

                            we’re going to pack this
                            container at the default
                            tk.TOP




Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack()




                                                                       pack a button




Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack()
                            tk.Button(root, text='Press me too!').pack()




                                                                       pack a button




Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack()
                            tk.Button(root, text='Press me too!').pack()
                            tk.Button(root, text='And me!').pack()




                                                                       pack a button




Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack(side=tk.LEFT)
                   tk.Button(root, text='Press me too!').pack(side=tk.LEFT)
                   tk.Button(root, text='And me!').pack(side=tk.LEFT)




                                                                     pack on tk.LEFT instead




Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack(side=tk.RIGHT)
                   tk.Button(root, text='Press me too!').pack(side=tk.RIGHT)
                   tk.Button(root, text='And me!').pack(side=tk.RIGHT)




                                                                     pack on tk.RIGHT instead




Saturday, 7 November 2009
more complex packing?



Saturday, 7 November 2009
tk.Button(root, text='Press me!').pack()
               horizontal = tk.Frame(root)
               horizontal.pack()
               tk.Button(horizontal, text='Press me too!').pack(side=tk.LEFT)
               tk.Button(horizontal, text='Press me too!').pack(side=tk.LEFT)




Saturday, 7 November 2009
grids



Saturday, 7 November 2009
tk.Button(root, text='Press me!').grid(row=0, column=0)
               tk.Message(root, text='Pressnmentoo!').grid(row=1, column=0)
               tk.Button(root, text='And me!').grid(row=1, column=1)




                                                          those are tk.CENTER “sticky”

                                                          other options are the 9 points of the compass

                                                          pack() also allows the sticky side to be specified

                                                          see I snuck in the multiline “Message” widget
                                                          there?




Saturday, 7 November 2009
... or place



Saturday, 7 November 2009
Widget values



Saturday, 7 November 2009
widgets with a variable
                            variable = tk.IntVar()
                            value = variable.get()
                            variable.set(value)




Saturday, 7 November 2009
text widgets
                            entry = tk.Entry()
                            value = entry.get()
                            entry.delete(0, tk.END)
                            entry.insert(0, value)




Saturday, 7 November 2009
list boxes
                            listbox = tk.Listbox(root)
                            listbox.pack()
                            for item in ‘one two three four’.split():
                                listbox.insert(tk.END, item)
                            selected = list.curselection()




Saturday, 7 November 2009
Styling



Saturday, 7 November 2009
2 methods:
                            1. direct
                            2. themed (py2.6+, py3k+)




Saturday, 7 November 2009
tk.Label(root, text="Hello, world!",
                                     background='black',
                                     foreground='white',
                                     font='Courier').pack()




Saturday, 7 November 2009
tk.Button(root, text="Hello, world!",
                                     background='black',
                                     foreground='white',
                                     font='Courier').pack()




                                                                    some limitations
                                                                    (sometimes depending on
                                                                    your theme)




Saturday, 7 November 2009
Option 2: Themed



Saturday, 7 November 2009
from [tT]kinter import ttk
                             lower-case “t” in py3k+

                             If you want it earlier you
                             can install the tile
                             extension




Saturday, 7 November 2009
complementary
                                  Though the themed widget commands work similarly to the originals,
                                  there are important differences.
                                  Themed widgets are not a drop-in replacement.
                                  In particular, themed widgets generally provide less options for
                                  customizing their appearance than regular Tk widgets (e.g. they will
                                  often not have options like "-background").
                                  Such changes, if needed (and they should be needed much less often)
                                  must be done by defining new widget styles, using the facilities offered
                                  by the themed widget package.



Saturday, 7 November 2009
Implements
                            button, checkbutton, entry, label,
                            menubutton, radiobutton, scale,
                              scrollbar, frame, labelframe,
                                      panedwindow




Saturday, 7 November 2009
Added
                            combobox, notebook,
                            progressbar, separator,
                                   sizegrip




Saturday, 7 November 2009
Not present
                             canvas, listbox,
                            menu, spinbox, text


                                                  these aren’t really
                                                  needed




Saturday, 7 November 2009
“classes” and “styles”
                            >>> from tkinter import ttk
                            >>> l = ttk.Label('hello, world!')
                            >>> l.winfo_class()
                            'TLabel'
                            >>> l['style']
                            ''




Saturday, 7 November 2009
layout example (button)



Saturday, 7 November 2009
>>> style = ttk.Style()
        >>> style.layout('TButton')
        [("Button.border", {"children": [("Button.focus", {"children":
        [("Button.spacing", {"children": [("Button.label", {"sticky":
        "nswe"})], "sticky": "nswe"})], "sticky": "nswe"})], "sticky":
        "nswe", "border": "1"})]	




Saturday, 7 November 2009
element options
     >>> style = ttk.Style()
     >>> style.element_options('Button.label')
     ('-compound', '-space', '-text', '-font', '-foreground', '-underline',
     '-width', '-anchor', '-justify', '-wraplength', '-embossed', '-image',
     '-stipple', '-background')




Saturday, 7 November 2009
style = ttk.Style()
          style.configure("Red.TLabel", foreground="red", font="Courier 32")
          ttk.Label(text="Test Styled", style="Red.TLabel").pack()
          ttk.Label(text="Test Unstyled").pack()




Saturday, 7 November 2009
switching themes
                            style = ttk.Style()
                            current_theme = style.theme_use()
                            new_theme = style.theme_create(...)
                            style.theme_use(new_theme)




Saturday, 7 November 2009
Events



Saturday, 7 November 2009
bind(), unbind()
                            def callback(event):
                                print "clicked at", event.x, event.y

                            frame = Frame(root, width=100, height=100)
                            frame.bind("<Button-1>", callback)




Saturday, 7 November 2009
<modifier-type-detail>



Saturday, 7 November 2009
mouse event types
                            mouse button    <Button-1>, <Button-2>, <Button-3>

                             mouse drag                <B1-Motion>

                            mouse release         <ButtonRelease-1>, ...

                             double click         <Double-Button-1>, ...

                             triple click         <Triple-Button-1>, ...

                        mouse entered                    <Enter>

                             mouse left                  <Leave>




Saturday, 7 November 2009
keyboard event types
                               focus         <FocusIn>, <FocusOut>

                                           <Enter>, <Delete>, <Left>,
                            specific keys          <Right>, ...

                              any key                <Key>

                              any text          a, b, 1, 2, ...

                                            <Shift-Up>, <Alt-Enter>,
                            modified keys       <Control-Tab>, ...




Saturday, 7 November 2009
special event types
                            configuration       <Configure>




                                           The widget changed size (or location, on some
                                           platforms). The new size is provided in the width
                                           and height attributes of the event object passed to
                                           the callback.




Saturday, 7 November 2009
Canvas
                            w = tk.Canvas(root, width=400, height=300)
                            w.pack()




Saturday, 7 November 2009
w.create_line(0, 0, 400, 300)




Saturday, 7 November 2009
w.create_line(0, 300, 400, 0,fill="red", dash=(4, 4))




Saturday, 7 November 2009
w.create_rectangle(150, 125, 250, 175, outline="green", fill="blue")




                                                       specify corders, outline and fill colors




Saturday, 7 November 2009
w.create_arc(50, 50, 200, 200, outline="blue", fill="green")




Saturday, 7 November 2009
w.create_oval(200, 200, 250, 250, outline="blue", fill="green")




Saturday, 7 November 2009
from PIL import Image, ImageTk
                            image = ImageTk.PhotoImage(Image.open('kitten.jpg'))
                            w.create_image((0, 0), image=image, anchor=tk.NW)




Saturday, 7 November 2009
Tips



Saturday, 7 November 2009
self.attributes('-topmost', True)




Saturday, 7 November 2009

Más contenido relacionado

La actualidad más candente

tkinter final ppt.ppt
tkinter final ppt.ppttkinter final ppt.ppt
tkinter final ppt.pptKanuAgrawal2
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderAshin Guha Majumder
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPriyaSoundararajan1
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In SqlAnurag
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide shareDevashish Kumar
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | EdurekaEdureka!
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Edureka!
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and ModulesRaginiJain21
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
Python Anaconda Tutorial | Edureka
Python Anaconda Tutorial | EdurekaPython Anaconda Tutorial | Edureka
Python Anaconda Tutorial | EdurekaEdureka!
 

La actualidad más candente (20)

Aggregate function
Aggregate functionAggregate function
Aggregate function
 
tkinter final ppt.ppt
tkinter final ppt.ppttkinter final ppt.ppt
tkinter final ppt.ppt
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
PYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.pptPYTHON - TKINTER - GUI - PART 1.ppt
PYTHON - TKINTER - GUI - PART 1.ppt
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Set operators
Set  operatorsSet  operators
Set operators
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
 
MySQL Introduction
MySQL IntroductionMySQL Introduction
MySQL Introduction
 
Matplotlib
MatplotlibMatplotlib
Matplotlib
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python Anaconda Tutorial | Edureka
Python Anaconda Tutorial | EdurekaPython Anaconda Tutorial | Edureka
Python Anaconda Tutorial | Edureka
 

Similar a Tkinter Does Not Suck

2009, o ano do Ruby on Rails no Brasil - CaelumDay 2009
2009, o ano do Ruby on Rails no Brasil - CaelumDay 20092009, o ano do Ruby on Rails no Brasil - CaelumDay 2009
2009, o ano do Ruby on Rails no Brasil - CaelumDay 2009Caue Guerra
 
Johnson at RubyConf 2008
Johnson at RubyConf 2008Johnson at RubyConf 2008
Johnson at RubyConf 2008jbarnette
 
Rhouse - Home automation is ruby ?
Rhouse - Home automation is ruby ?Rhouse - Home automation is ruby ?
Rhouse - Home automation is ruby ?Fernand Galiana
 
Apache Hadoop Talk at QCon
Apache Hadoop Talk at QConApache Hadoop Talk at QCon
Apache Hadoop Talk at QConCloudera, Inc.
 
Oxente on Rails 2009
Oxente on Rails 2009Oxente on Rails 2009
Oxente on Rails 2009Fabio Akita
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)OpenBlend society
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Matt Aimonetti
 
Conquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSConquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSCaridy Patino
 
Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Skills Matter
 
How OpenNTF Open Source Solutions Can Save You Time, Money And Your Hair
How OpenNTF Open Source Solutions Can Save You Time, Money And Your HairHow OpenNTF Open Source Solutions Can Save You Time, Money And Your Hair
How OpenNTF Open Source Solutions Can Save You Time, Money And Your HairBruce Elgort
 
The Open-PC - OpenSourceExpo 2009
The Open-PC - OpenSourceExpo 2009The Open-PC - OpenSourceExpo 2009
The Open-PC - OpenSourceExpo 2009Frank Karlitschek
 
A Look at the Future of HTML5
A Look at the Future of HTML5A Look at the Future of HTML5
A Look at the Future of HTML5Tim Wright
 
DjangoCon 2009 Keynote
DjangoCon 2009 KeynoteDjangoCon 2009 Keynote
DjangoCon 2009 KeynoteTed Leung
 

Similar a Tkinter Does Not Suck (20)

2009, o ano do Ruby on Rails no Brasil - CaelumDay 2009
2009, o ano do Ruby on Rails no Brasil - CaelumDay 20092009, o ano do Ruby on Rails no Brasil - CaelumDay 2009
2009, o ano do Ruby on Rails no Brasil - CaelumDay 2009
 
Johnson at RubyConf 2008
Johnson at RubyConf 2008Johnson at RubyConf 2008
Johnson at RubyConf 2008
 
Rhouse - Home automation is ruby ?
Rhouse - Home automation is ruby ?Rhouse - Home automation is ruby ?
Rhouse - Home automation is ruby ?
 
Apache Hadoop Talk at QCon
Apache Hadoop Talk at QConApache Hadoop Talk at QCon
Apache Hadoop Talk at QCon
 
Vagrant at LA Ruby
Vagrant at LA RubyVagrant at LA Ruby
Vagrant at LA Ruby
 
Rejectkaigi 2010
Rejectkaigi 2010Rejectkaigi 2010
Rejectkaigi 2010
 
Oxente on Rails 2009
Oxente on Rails 2009Oxente on Rails 2009
Oxente on Rails 2009
 
JavaSE 7
JavaSE 7JavaSE 7
JavaSE 7
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
 
Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010Macruby - RubyConf Presentation 2010
Macruby - RubyConf Presentation 2010
 
05 subsetting
05 subsetting05 subsetting
05 subsetting
 
Caridy patino - node-js
Caridy patino - node-jsCaridy patino - node-js
Caridy patino - node-js
 
Conquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JSConquistando el Servidor con Node.JS
Conquistando el Servidor con Node.JS
 
21 Polishing
21 Polishing21 Polishing
21 Polishing
 
Akka scalaliftoff london_2010
Akka scalaliftoff london_2010Akka scalaliftoff london_2010
Akka scalaliftoff london_2010
 
How OpenNTF Open Source Solutions Can Save You Time, Money And Your Hair
How OpenNTF Open Source Solutions Can Save You Time, Money And Your HairHow OpenNTF Open Source Solutions Can Save You Time, Money And Your Hair
How OpenNTF Open Source Solutions Can Save You Time, Money And Your Hair
 
The Open-PC - OpenSourceExpo 2009
The Open-PC - OpenSourceExpo 2009The Open-PC - OpenSourceExpo 2009
The Open-PC - OpenSourceExpo 2009
 
RubyConf 2009
RubyConf 2009RubyConf 2009
RubyConf 2009
 
A Look at the Future of HTML5
A Look at the Future of HTML5A Look at the Future of HTML5
A Look at the Future of HTML5
 
DjangoCon 2009 Keynote
DjangoCon 2009 KeynoteDjangoCon 2009 Keynote
DjangoCon 2009 Keynote
 

Más de Richard Jones

Introduction to Game Programming
Introduction to Game ProgrammingIntroduction to Game Programming
Introduction to Game ProgrammingRichard Jones
 
Message Queueing - by an MQ noob
Message Queueing - by an MQ noobMessage Queueing - by an MQ noob
Message Queueing - by an MQ noobRichard Jones
 
Web micro-framework BATTLE!
Web micro-framework BATTLE!Web micro-framework BATTLE!
Web micro-framework BATTLE!Richard Jones
 
Intro to Game Programming
Intro to Game ProgrammingIntro to Game Programming
Intro to Game ProgrammingRichard Jones
 
Introduction to Game Programming Tutorial
Introduction to Game Programming TutorialIntroduction to Game Programming Tutorial
Introduction to Game Programming TutorialRichard Jones
 
State of Python (2010)
State of Python (2010)State of Python (2010)
State of Python (2010)Richard Jones
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6Richard Jones
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5Richard Jones
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4Richard Jones
 

Más de Richard Jones (12)

Angboard
AngboardAngboard
Angboard
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Introduction to Game Programming
Introduction to Game ProgrammingIntroduction to Game Programming
Introduction to Game Programming
 
Message Queueing - by an MQ noob
Message Queueing - by an MQ noobMessage Queueing - by an MQ noob
Message Queueing - by an MQ noob
 
Message queueing
Message queueingMessage queueing
Message queueing
 
Web micro-framework BATTLE!
Web micro-framework BATTLE!Web micro-framework BATTLE!
Web micro-framework BATTLE!
 
Intro to Game Programming
Intro to Game ProgrammingIntro to Game Programming
Intro to Game Programming
 
Introduction to Game Programming Tutorial
Introduction to Game Programming TutorialIntroduction to Game Programming Tutorial
Introduction to Game Programming Tutorial
 
State of Python (2010)
State of Python (2010)State of Python (2010)
State of Python (2010)
 
What's New In Python 2.6
What's New In Python 2.6What's New In Python 2.6
What's New In Python 2.6
 
What's New In Python 2.5
What's New In Python 2.5What's New In Python 2.5
What's New In Python 2.5
 
What's New In Python 2.4
What's New In Python 2.4What's New In Python 2.4
What's New In Python 2.4
 

Último

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Tkinter Does Not Suck

  • 1. Tkinter doesn’t suck! Honest! Saturday, 7 November 2009
  • 2. “What GUI toolkit should I use?” – random poster in random forum Saturday, 7 November 2009
  • 4. import wx class Application(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, -1, 'My GUI', size=(300, 200)) panel = wx.Panel(self) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) txt = wx.StaticText(panel, -1, 'Hello, world') sizer.Add(txt, 0, wx.TOP|wx.LEFT, 20) self.Centre() self.Show(True) app = wx.App(0) Application(None) app.MainLoop() Saturday, 7 November 2009
  • 6. import gtk window = gtk.Window() label = gtk.Label("Hello, world") window.add(label) window.show_all() gtk.main() Saturday, 7 November 2009
  • 8. import sys import PyQt4.Qt as qt a=qt.QApplication(sys.argv) w=qt.QLabel("Hello, world") w.show() a.exec_() Saturday, 7 November 2009
  • 12. import Tkinter as tk root = tk.Tk() tk.Label(root, text="Hello, world").pack() root.mainloop() Saturday, 7 November 2009
  • 13. “yeah, OMG, Tkinter sucks!” Saturday, 7 November 2009
  • 14. I disagree Saturday, 7 November 2009
  • 15. 1. it’s simple to use - rich base widget set - which is not verbose - automatic packing Saturday, 7 November 2009
  • 16. 2. it’s always there on Windows & OS X -- on Linuxes you might need to install an optional package Saturday, 7 November 2009
  • 17. 3. it’s mature first release 1991 8.0 released August 1999 8.5 released December 2007 Saturday, 7 November 2009
  • 18. how I discovered this I had this project that I wanted to be click-to-run, but needed to select a file Looked for a cross-platform “file dialog” solution and found some hacks Then I noticed a reference to Tkinter, and lo and behold... Saturday, 7 November 2009
  • 19. filename = tkFileDialog.askopenfilename(parent=root, filetypes=[('ReStructuredText Files', '.rst .txt'), ('All Files', '.*')], title='Select your presentation file') Saturday, 7 November 2009
  • 21. well, if it can do that... what about the program’s command-line options? Saturday, 7 November 2009
  • 23. self.root = tk.Tk() frame = Tk.Frame(self.root) frame.pack() Tk.Label(frame, text='Bruce, the Presentation Tool!').pack() self.fullscreen = Tk.IntVar() Tk.Checkbutton(frame, text='Fullscreen?', variable=self.fullscreen).pack() # screen selection display = pyglet.window.get_platform().get_default_display() N = len(display.get_screens()) self.screen = Tk.IntVar(0) if N > 1: for n in range(N): Tk.Radiobutton(frame, text="Display on screen %d"%(n+1), variable=self.screen, value=n).pack() self.timer = Tk.IntVar() Tk.Checkbutton(frame, text='Show Timer?', variable=self.timer).pack() self.page_count = Tk.IntVar() Tk.Checkbutton(frame, text='Show Page Count?', variable=self.page_count).pack() self.bullet_mode = Tk.IntVar() Tk.Checkbutton(frame, text='Run in Bullet Mode?', variable=self.bullet_mode).pack() self.source = Tk.IntVar() Tk.Checkbutton(frame, text='Display source in console?', variable=self.source).pack() Tk.Button(frame, text='Play Presentation', command=self.go).pack() Saturday, 7 November 2009
  • 25. 1. it’s not pretty Saturday, 7 November 2009
  • 26. 1. it’s not pretty 1. it doesn’t look native, 2. fonts are not anti-aliased Saturday, 7 November 2009
  • 27. 2. extending is tricky Saturday, 7 November 2009
  • 28. native look and feel (since Tk 8.0, 1999) Saturday, 7 November 2009
  • 29. native look and feel (since Tk 8.0, 1999) (much improved in Tk 8.5, 2008) Saturday, 7 November 2009
  • 30. native look and feel (since Tk 8.0, 1999) (much improved in Tk 8.5, 2008) (“less ugly but not perfect”) Saturday, 7 November 2009
  • 33. truetype / opentype fonts (since Tk 8.5) Saturday, 7 November 2009
  • 34. 1. Simple to use Saturday, 7 November 2009
  • 36. import Tkinter as tk root = tk.Tk() tk.Label(root, text="Hello, world").pack() root.mainloop() demo image display label properties: foreground, background, font, ??? Saturday, 7 November 2009
  • 37. import Tkinter as tk root = tk.Tk() tk.Label(root, text="Hello, world").pack() root.mainloop() No point showing the other three lines in other examples Saturday, 7 November 2009
  • 38. from PIL import Image, ImageTk image = ImageTk.PhotoImage(Image.open('kitten.jpg')) tk.Label(root, image=image).pack() Saturday, 7 November 2009
  • 39. def pressed(): print 'You pressed me!' tk.Button(root, text='Press me!', command=pressed).pack() Saturday, 7 November 2009
  • 40. entry = tk.Entry(root) entry.pack() entry.insert(0, 'some text') Saturday, 7 November 2009
  • 41. value = tk.IntVar() tk.Checkbutton(root, text='Checked?', variable=value).pack() Saturday, 7 November 2009
  • 42. value = tk.IntVar() for n in range(4): tk.Radiobutton(root, value=n text="Selection %d"%(n+1), variable=value).pack() Saturday, 7 November 2009
  • 43. value = tk.StringVar(value='One') tk.OptionMenu(root, value, 'One', 'Two', 'Three').pack() 10 minutes Saturday, 7 November 2009
  • 44. listbox = tk.Listbox(root) listbox.pack() listbox.insert(tk.END, "a list entry") for item in ‘one two three four’.split(): listbox.insert(tk.END, item) Saturday, 7 November 2009
  • 45. text = tk.Text(root) text.pack() text.insert(tk.END, '''some text more text''') also allows: - embedding of images and widgets - searching - tagging (identification, useful for properties) - styles Saturday, 7 November 2009
  • 46. scale = tk.Scale(root, from_=0, to=100) scale.pack() Saturday, 7 November 2009
  • 47. w = tk.Canvas(root, width=200, height=100) w.pack() w.create_line(0, 0, 200, 100) w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) w.create_rectangle(50, 25, 150, 75, fill="blue") - line (with arrows), arc, image, oval, polygon, rectangle, text, widgets - outline, fill - scrollable (limitable) - picking (with closest) Saturday, 7 November 2009
  • 48. 1. Simple to use Saturday, 7 November 2009
  • 50. rows or columns the pack manager packs into rows or columns the default is column, centered. Saturday, 7 November 2009
  • 51. in the beginning there is a container, and it is empty we’re going to pack this container at the default tk.TOP Saturday, 7 November 2009
  • 52. tk.Button(root, text='Press me!').pack() pack a button Saturday, 7 November 2009
  • 53. tk.Button(root, text='Press me!').pack() tk.Button(root, text='Press me too!').pack() pack a button Saturday, 7 November 2009
  • 54. tk.Button(root, text='Press me!').pack() tk.Button(root, text='Press me too!').pack() tk.Button(root, text='And me!').pack() pack a button Saturday, 7 November 2009
  • 55. tk.Button(root, text='Press me!').pack(side=tk.LEFT) tk.Button(root, text='Press me too!').pack(side=tk.LEFT) tk.Button(root, text='And me!').pack(side=tk.LEFT) pack on tk.LEFT instead Saturday, 7 November 2009
  • 56. tk.Button(root, text='Press me!').pack(side=tk.RIGHT) tk.Button(root, text='Press me too!').pack(side=tk.RIGHT) tk.Button(root, text='And me!').pack(side=tk.RIGHT) pack on tk.RIGHT instead Saturday, 7 November 2009
  • 58. tk.Button(root, text='Press me!').pack() horizontal = tk.Frame(root) horizontal.pack() tk.Button(horizontal, text='Press me too!').pack(side=tk.LEFT) tk.Button(horizontal, text='Press me too!').pack(side=tk.LEFT) Saturday, 7 November 2009
  • 60. tk.Button(root, text='Press me!').grid(row=0, column=0) tk.Message(root, text='Pressnmentoo!').grid(row=1, column=0) tk.Button(root, text='And me!').grid(row=1, column=1) those are tk.CENTER “sticky” other options are the 9 points of the compass pack() also allows the sticky side to be specified see I snuck in the multiline “Message” widget there? Saturday, 7 November 2009
  • 61. ... or place Saturday, 7 November 2009
  • 62. Widget values Saturday, 7 November 2009
  • 63. widgets with a variable variable = tk.IntVar() value = variable.get() variable.set(value) Saturday, 7 November 2009
  • 64. text widgets entry = tk.Entry() value = entry.get() entry.delete(0, tk.END) entry.insert(0, value) Saturday, 7 November 2009
  • 65. list boxes listbox = tk.Listbox(root) listbox.pack() for item in ‘one two three four’.split(): listbox.insert(tk.END, item) selected = list.curselection() Saturday, 7 November 2009
  • 67. 2 methods: 1. direct 2. themed (py2.6+, py3k+) Saturday, 7 November 2009
  • 68. tk.Label(root, text="Hello, world!", background='black', foreground='white', font='Courier').pack() Saturday, 7 November 2009
  • 69. tk.Button(root, text="Hello, world!", background='black', foreground='white', font='Courier').pack() some limitations (sometimes depending on your theme) Saturday, 7 November 2009
  • 70. Option 2: Themed Saturday, 7 November 2009
  • 71. from [tT]kinter import ttk lower-case “t” in py3k+ If you want it earlier you can install the tile extension Saturday, 7 November 2009
  • 72. complementary Though the themed widget commands work similarly to the originals, there are important differences. Themed widgets are not a drop-in replacement. In particular, themed widgets generally provide less options for customizing their appearance than regular Tk widgets (e.g. they will often not have options like "-background"). Such changes, if needed (and they should be needed much less often) must be done by defining new widget styles, using the facilities offered by the themed widget package. Saturday, 7 November 2009
  • 73. Implements button, checkbutton, entry, label, menubutton, radiobutton, scale, scrollbar, frame, labelframe, panedwindow Saturday, 7 November 2009
  • 74. Added combobox, notebook, progressbar, separator, sizegrip Saturday, 7 November 2009
  • 75. Not present canvas, listbox, menu, spinbox, text these aren’t really needed Saturday, 7 November 2009
  • 76. “classes” and “styles” >>> from tkinter import ttk >>> l = ttk.Label('hello, world!') >>> l.winfo_class() 'TLabel' >>> l['style'] '' Saturday, 7 November 2009
  • 78. >>> style = ttk.Style() >>> style.layout('TButton') [("Button.border", {"children": [("Button.focus", {"children": [("Button.spacing", {"children": [("Button.label", {"sticky": "nswe"})], "sticky": "nswe"})], "sticky": "nswe"})], "sticky": "nswe", "border": "1"})] Saturday, 7 November 2009
  • 79. element options >>> style = ttk.Style() >>> style.element_options('Button.label') ('-compound', '-space', '-text', '-font', '-foreground', '-underline', '-width', '-anchor', '-justify', '-wraplength', '-embossed', '-image', '-stipple', '-background') Saturday, 7 November 2009
  • 80. style = ttk.Style() style.configure("Red.TLabel", foreground="red", font="Courier 32") ttk.Label(text="Test Styled", style="Red.TLabel").pack() ttk.Label(text="Test Unstyled").pack() Saturday, 7 November 2009
  • 81. switching themes style = ttk.Style() current_theme = style.theme_use() new_theme = style.theme_create(...) style.theme_use(new_theme) Saturday, 7 November 2009
  • 83. bind(), unbind() def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100) frame.bind("<Button-1>", callback) Saturday, 7 November 2009
  • 85. mouse event types mouse button <Button-1>, <Button-2>, <Button-3> mouse drag <B1-Motion> mouse release <ButtonRelease-1>, ... double click <Double-Button-1>, ... triple click <Triple-Button-1>, ... mouse entered <Enter> mouse left <Leave> Saturday, 7 November 2009
  • 86. keyboard event types focus <FocusIn>, <FocusOut> <Enter>, <Delete>, <Left>, specific keys <Right>, ... any key <Key> any text a, b, 1, 2, ... <Shift-Up>, <Alt-Enter>, modified keys <Control-Tab>, ... Saturday, 7 November 2009
  • 87. special event types configuration <Configure> The widget changed size (or location, on some platforms). The new size is provided in the width and height attributes of the event object passed to the callback. Saturday, 7 November 2009
  • 88. Canvas w = tk.Canvas(root, width=400, height=300) w.pack() Saturday, 7 November 2009
  • 89. w.create_line(0, 0, 400, 300) Saturday, 7 November 2009
  • 90. w.create_line(0, 300, 400, 0,fill="red", dash=(4, 4)) Saturday, 7 November 2009
  • 91. w.create_rectangle(150, 125, 250, 175, outline="green", fill="blue") specify corders, outline and fill colors Saturday, 7 November 2009
  • 92. w.create_arc(50, 50, 200, 200, outline="blue", fill="green") Saturday, 7 November 2009
  • 93. w.create_oval(200, 200, 250, 250, outline="blue", fill="green") Saturday, 7 November 2009
  • 94. from PIL import Image, ImageTk image = ImageTk.PhotoImage(Image.open('kitten.jpg')) w.create_image((0, 0), image=image, anchor=tk.NW) Saturday, 7 November 2009