Python and Tkinter

Tkinter is the standard GUI-package for python and is a object-orientated layer above Tcl/Tk. So if you know, how to describe a GUI with Tcl/Tk in C, it should be no problem for you to do it in python.

To start with it you can create a simple program with:

#!/usr/bin/python

from Tkinter import * < – You will need to import all functions, a simple import Tkinter will not be sufficient.

root = Tk() <- This creates a start widget to put in all other widgets (buttons, images, menus, etc.).

label = Label(root, text=”hello world”) <- To create a Label you need to put it into a reference and give it some options.

label.pack() <- Now you can use one of three options to put it in the main frame. Here we obviously use pack.

root.mainloop() <- With this method you start the event handler of Tkinter (for key press and mouse clicks). Also this is important for Tkinter to create the application itself and to update it.

As mentioned above you can put your widgets via three different methods. There pack, grid and place. These are geometry manager and the allow you to postion the widgets where you want. Pack organizes the wigdets how they come and fit together the best way it can make out (you should try yourself). Grid works like a grid and you can directly control how many rows and columns a widget needs. Place gives you full controll where to put the widgets, so it is a lot of work.

With the bind-method you can capture any mouse or keyboard events you like.

root.bind(‘<Escape>’, lambda e: root.quit()) <- This binds the escape-key to the quit function, instead of lambda you can use any other function.

So now we have settled the basics we can get to the bigger program. It is a simple calculator for the four basic operations +, -, *, /.  It uses binds for the different buttons. Also there is a rudimental menu.  I created a class for the calculator to hold all the functions in one object.  In the main procedure I create a root widget, which I pass over to the new object calc. This creates in it __init__method the layout with a label for the result, the different buttons in a maximum of four rows and a menu with a quit option. Furthermore the buttons get bind to a function and after it I run the mainloop and create the application. The destroy method is not necessary, but should be used in some development environments. The widget are object, so you can get and set the attributes of an object. But after its creation you can alter these with the configure-method.  Another important point to know is, that you need special variables of Tkinter for interactive text. There are three different types (String, Boolean, Integer).

lambda are anomynous functions which are not bound to name. so they cannot be called from everywhere. Additionally there is no switch function in python, but you can use a dictionary for that. You just need to use your switch-case as keyword for the dictionary. But then every function needs to have the same amount of arguments or you use some padding-variables.

#!/usr/bin/python

from Tkinter import *

class Calculon:

def __init__(self, master):

buttonText = [“1”, “2”, “3”, “+”, “4”, “5”, “6”, “-“, “7”, “8”, “9”, “*”, “0”, “.”, “=”, “/”]

master.bind(‘<Escape>’, lambda e: master.quit())
master.bind(‘<Return>’, lambda e: self.buttonPress(“=”))

for each in buttonText:
master.bind(each, lambda e: self.buttonPress(repr(e.char).strip(“‘”)))

self.resultText = StringVar()
self.resultText.set(“0″)
self.result = Label(master, anchor=E, textvariable=self.resultText, justify=RIGHT, bg=”white”)
self.result.grid(row=0, column=0, columnspan=4, sticky=E+N+S+W)
self.operatorText = StringVar()
self.operatorText.set(“”)
self.operator = Label(master, anchor=W, textvariable=self.operatorText, justify=LEFT, bg=”grey”)
self.operator.grid(row=0, column=0, sticky=W+N+S+E)
self.temp = “”
self.operations = {“+”: self.add, “-“: self.sub, “*”: self.mul, “/”:self.div}

self.menubar = Menu(master)
self.pullDown = Menu(self.menubar, tearoff=0)
self.pullDown.add_separator()
self.pullDown.add_command(label=”Quit”, command=master.quit)
self.menubar.add_cascade(label=”Do it”, menu=self.pullDown)
master.configure(menu=self.menubar)

rowC = 1
colC = 0
for item in buttonText:
if colC > 3:
colC = 0
rowC = rowC + 1
Button(master, text=str(item), command=lambda i=item:self.buttonPress(i)).grid(row=rowC, column=colC)
colC = colC + 1

def add(self, a, b):
return a+b

def sub(self, a, b):
return a-b

def mul(self, a, b):
return a*b

def div(self, a, b):
if b != 0:
return a/b
else:
return “division by zero”

def buttonPress(self, c):
if ((ord(c) > 47) and (ord(c) < 58)) or (ord(c) == 46):
if len(self.resultText.get()) > 10:
return -1
if self.resultText.get() != “0”:
self.resultText.set(self.resultText.get() + c)
else:
self.resultText.set(c)
elif (ord(c) > 41) and (ord(c) < 48) or ord(c) == 61:
if self.operatorText.get() == “” or self.operatorText.get() == “=”:
self.operatorText.set(c)
self.temp = int(self.resultText.get())
self.resultText.set(“0″)
else:
result = self.operations[self.operatorText.get()](self.temp, int(self.resultText.get()))
if result < 0:
self.result.configure(fg=”red”)
else:
self.result.configure(fg=”black”)
self.resultText.set(str(result))
self.operatorText.set(c)

def main():
root = Tk()
calc = Calculon(root)

root.mainloop()
root.destroy()

if __name__ == “__main__”:
main()

All in all the calculator is quite incomplete. You can compute decimal values, also the menu is quite useless and instead of a label you could use a entry widget (editbox) for entering numbers. A few more functions for extracting the root or squaring would be useful too. But I think it is a good start to play around with the different opportunities which Tkinter you give.

sources:

http://effbot.org/tkinterbook/ (with a good references for most of the options of a lot methods)

http://www.daniweb.com/software-development/python/threads/166751

calc – source code to ownload as pdf with all intends <:

Advertisements

~ by frankooh on 2011-06-06T10:24:02+00:00.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: