Continuing our series of desktop GUIs, in this post we are going to go over the topic of building a small hello world program using Python Tkinter.
What is Tkinter ?
Tkinter is python wrapper/binding to Tk library. Tk was developed as GUI library for Tcl language by John Ousterhout. For many other high level language authors coming to programming scene in 1990s this seemed like easy tool to capitalize on in bringing GUI library to their language. That’s why you can find many different language bindings to Tk. Tk brought easy GUI building to programming masses.
Often times many people write off Tk or Tkinter as ugly old GUI library. Their claims are not completely unfounded. But, Tk in recent time made strides to bring modern look to Tk by implementing Tile, themeing engine to Tk. Tile is also called as ttk. With ttk in place look and feel issues of Tk are addressed.
Tile xp blue theme demoBut, Tkinter still lags behind in terms available collection of default widgets compared to other libraries like PySide or wxPython . However, Tkinter is still a good candidate if you quickly want to dish out a GUI without having programming styles imposed on you. (You will see these style restrictions in our next posts about wxPython and PySide)
Hello world
Now, we will go over building a simple hello world program using Tkinter. In this program we will create a simple window with “Hello world” text in it. And a button that say “Kill Me”. Clicking that button will cause the python program to exit.
from Tkinter import * root = Tk() l = Label(text="Hello world", font=("Helvetica", 20)) l.pack() b = Button(text="Kill Me", command=sys.exit) b.pack() root.mainloop()
That import * line saves your some typing.
root = Tk()
This line instantiates Tk and creates main window of the program. Next we create a Label (a widget which displays text ) and call it’s pack method. pack is one three available layout methods provided by Tkinter (rest of the two being grid and place). The widget will not show up until you call pack. Next, we create a Button widget and pack it, similar to that of Label. The interesting point to note while creating button widget is, we provide command argument to it with a reference of sys.exit function. A newbie mistake that is often made is, passing function with () next to it. That will cause the target function to be invoked immediately. You are only supposed to pass the reference of function and Tkinter will call it when button is pressed. So, when this “Kill Me” button is pressed sys.exit will be called and program exits. One, last important line to notice is root.mainloop() . This line sets the event monitoring loop in motion and Tkinter take control of the program from here.
The post Building hello world using Python Tkinter appeared first on Lintel Technologies Blog.