Dev: March 2009 Archives

Tkinter

|
As part of my continuing effort to hate Python less, I decided to do some fiddling with the Python Tkinter library.  For those of you playing along at home, it's a series of libraries (or whatever Python calls them) for performing Tk/Tcl tasks.  

I've never done GUI coding before.  Up to this point, all my code's execution space was limited to browsers and the occasional CLI tool.  Like one would expect from an object-oriented language, the GUI behaves in much the same fashion, with 'widgets' as they are called (a button, a menu, text field, etc.) descend from a root frame.

from Tkinter import *  # Get the library

class App:

    # Draw GUI and init
    def __init__(self, master):

        # Parent frame
        frame = Frame(master)

        # The pack() method returns an object of type None so Frame(master).pack() will only work if you don't want to reference 'frame' again.
        frame.pack()
   
        # Labels are simply output areas
        self.display_text = Label(frame,text="")
   
        # side=TOP - Sets the widget's placement
        # TOP, BOTTOM, LEFT, and RIGHT are constants set by Tk
        self.display_text.pack(side=TOP)

        # Create a button
        # Args:
        #  frame - Set 'frame' as the parent of the button
        #  text - an attribute setting the text on the button
        #  command - the callback which will fire when the button is clicked.
        self.button = Button(frame, text="This is a button", command=self.a_method)
        self.button.pack(side=LEFT)

    # A callback method
    def a_method(self):
   
        # the config() (or configure() ) method is used to modify widget options
        self.display_text.config(text="Button pressed")

#Yet another thing I hate about Python - if the next four lines are at the top of the file, this doesn't work.
root = Tk() #Instantiate the root widget
root.title('Test App')  # ...and give the window a title
app = App(root)  #Instantiate the App class, which contains all the logic
root.mainloop() # Start the event handling loop

Much like in CSS, object placement seems to get exponentially more troublesome as the number of objects grow. 

While so far the only thing I've done with this is write a utility for work (and thereby getting some more practice with Python's xmlrpclib methods) I think I'll definitely have to keep messing around with this.

Play around with it a bit and let me know what you end up creating!

About this Archive

This page is a archive of entries in the Dev category from March 2009.

Dev: February 2009 is the previous archive.

Find recent content on the main index or look in the archives to find all content.