Tkinter, pronounced tee kay inter is the in-built Graphical User Interface(GUI – buttons etc) package for python
Though powerful, it is not well known. It is also surprisingly easy …
How powerful is tkinter?
Well the IDLE, the interactive prompt of python … has been built with tkinter
Which python version do i use tkinter with?
As from python 3.4 it is really good. Better start with that.
How do i know if i have tkinter?
for python 2 type in the idle import Tkinter . for python 3 : import tkinter. see the T difference
if you have it, it will continue to the next line. else you will get :
Traceback (most recent call last):
File “”, line 1, in
ImportError: No module named ‘tkinter’
i tested with python 3.4 on windows, it was already installed
Thinking the tkinter way
Well for gui’s in general, i prefer design the gui first on paper or whatever then to worry about the code. The other way round is a bit absurd. Maybe it’s like that for me as in android studio or visual studio, for android development, you have the option to drag and drop the components and fit it on the screen. But in general, better get an idea of what you want then proceed. so,
1 plan your layout first
2 write the events you want to happen
3. bind the above to the component.
Don’t worry, illustrations coming . . .
Tkinter – the basic code
note : this and until the end is for python 3.4 .
You will see this after running the above:
3 lines of code or 6 words you get a nice gui . . .
Now, that title needs abit of customisation. add this :
and the result is this:
Concerning the placement of components.
There are 3 ways to place buttons etc.
- pack() method
- grid() method
- place() method
The easiest way is to use pack()
grid() offers a better placement
place() is used for absolute placement i.e. exactly where you want it to be
Note : whatever you can do with grid() you can do with pack(). However, it is added complexity.
Now let us add a label. a label is a piece of text
but that is not enough, you must put this also:
and you get that:
A bit of explanation :
piece_of_text = Label(window, text='starting tkinter') #the window says you want to put in in the window named window. #the pack fits the windoe=w to the text
the piece_of_text.pack() can be thought to put it in the window. But the pack() method also accept more parameters which will be i a discussed!
The window is very small, it fits only the text. but don’t worry, you can exactly specify the size you want.
However, you can also write:
It’s just a difference of reference. both works but dividing in two parts is better.
Our code upto now:
What does widget means?
Widget is a word you will hear a lot. it’s just a mix of window and gadget
dow + gadget = widget