Loading...
Uncategorized

Python – Building GUIs – TK/TTK/Tkinter

If you’re going to write a series of articles on GUI design and implementation you might as well start from the beginning with Tkinter/TK pythons defacto GUI framework. Almost since the beginning the developers of python knew there woud be a need for a GUI frame work so they adapted tcl/tk for use with python by including a tcl interpreter into python. While it is functionhal and effective it did have a few draw backs being that it wasn’t very robust, included the most basic of widgets, didn’t look very good (think back to the early days of any X11 window manager and how unappealing their dialogs looked, and could be slow running.

In recent years a lot of Tkinter has been rewritten to be faster , include more widgets and support better theming so the dialogs will look less out of place on windows, linux and mac. The benfit of using tkinter is that it is almost always installed by default with python so usability from system to system is almost guaranteed even if you forgot to build your application package to include it’s module. While it is still a little underfeatured if all you need are some simple dialogs the the basic controls you would expect from the average dialog driven application Tkinter is still quite effectice and easy to implement without much experience, allowing you to create and use dialogs in your applications very quickly and effortlessly.

This article does not aim to be a complete reference to using Tkinter but only to show a few basic examples, basic features and provide links to other tutorials and reference materials. Tkinter provides the following widgets several of which are updated and overridden through TTK.

Button The Button widget is used to display buttons in your application.

CanvasThe Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application.

CheckbuttonThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time.

EntryThe Entry widget is used to display a single-line text field for accepting values from a user.

FrameThe Frame widget is used as a container widget to organize other widgets.

LabelThe Label widget is used to provide a single-line caption for other widgets. It can also contain images.

ListboxThe Listbox widget is used to provide a list of options to a user.

MenubuttonThe Menubutton widget is used to display menus in your application.

MenuThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.

MessageThe Message widget is used to display multiline text fields for accepting values from a user.

RadiobuttonThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time.

ScaleThe Scale widget is used to provide a slider widget.ScrollbarThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.

TextThe Text widget is used to display text in multiple lines.

ToplevelThe Toplevel widget is used to provide a separate window container.

SpinboxThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values.

PanedWindowA PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically.

LabelFrameA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts.

tkMessageBoxThis module is used to display message boxes in your applications.

The following are expanded widgets in TTK.

ttk.Button

ttk.Checkbutton

ttk.Combobox

ttk.Entry

ttk.Frame

ttk.Label

ttk.LabelFrame

ttk.Menubutton

ttk.Notebook

ttk.PanedWindow

ttk.Progressbar

ttk.Radiobutton

ttk.Scale

ttk.Scrollbar

ttk.Separator

ttk.Sizegrip

ttk.Treeview

It starts with Hello.

As with every programming or scripting tutorial we are going to create a hello world program. In this case we are going to create a simple window with a button that when clicked will cause a popup dialog

import Tkinter
import tkMessageBox

root = Tkinter.Tk()

def OnButtonClick():

tkMessageBox.showinfo( “Hello Python”, “Hello World”)

button = Tkinter.Button(root, text =”Click Me!”, command = OnButtonClick)

button.pack()

root.mainloop()

It’s that simple to create a dialog box, tkinter was designed to be simple and easy to use, the following example will demonstrate taking input through a text box and changing the text in a label when a button is clicked

 

#!/usr/bin/python

# -*- coding: iso-8859-1 -*-

import Tkinter

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky=’EW’)
        self.entry.bind(“<Return>”, self.OnPressEnter)
        self.entryVariable.set(u”Enter text here.”)

        button = Tkinter.Button(self,text=u”Click me !”,
                                command=self.OnButtonClick)
        button.grid(column=1,row=0)

        self.labelVariable = Tkinter.StringVar()
        label = Tkinter.Label(self,textvariable=self.labelVariable,
                              anchor=”w”,fg=”white”,bg=”blue”)
        label.grid(column=0,row=1,columnspan=2,sticky=’EW’)
        self.labelVariable.set(u”Hello !”)

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())       
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnButtonClick(self):
        self.labelVariable.set( self.entryVariable.get()+” (You clicked the button)” )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnPressEnter(self,event):
        self.labelVariable.set( self.entryVariable.get()+” (You pressed ENTER)” )
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

if __name__ == “__main__”:
    app = simpleapp_tk(None)
    app.title(‘my application’)
    app.mainloop()

handling events and creating key bindings is east and quick in the code samoke below we create a windo window and we create a binding to button 1 on your mouse./

 

from Tkinter import *
root = Tk()
def callback(event):    print “clicked at”, event.x, event.y
frame = Frame(root, width=100, height=100)
frame.bind(“<Button-1>”, callback)

frame.pack()

root.mainloop()

 

You can find more information on Tkinter at the following sites.

An non-official  manual and reference for tkinter, very complete in providing information on all of tkinters features,

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html

Tkinter examples and tutorials can be found at
http://www.openbookproject.net/py4fun/gui/tkPhone.html

http://www.tkdocs.com/tutorial/firstexample.html

 

A great book on tkinter can be found at
http://www.asiaa.sinica.edu.tw/~ctli/python-and-tkinter-programming.pdf

This book goes into great detail on explaining all of the features of tkinter.

Popular Posts
  • No Popular Post Available
Leave a Reply

Your email address will not be published. Required fields are marked *

*