Welcome, Guest. Please login or register.
Pages: [1]
  Print  
Author Topic: GUIs in Python: A TKinter Tutorial  (Read 8952 times)
Spy
Administrator
Hero Member
*****

Karma: 70
Posts: 182



View Profile WWW
« on: August 16, 2010, 10:32:21 PM »

Hey guys, this tutorial is about making a basic GUI for your programs in Python using the Tkinter module. Alright, let's get started!

So what do I need?
Well, if you followed my last tutorial, you should have downloaded Python 2.6; if not, you can download it here: http://python.org/
If you do have 2.6, then you already have the module that we will be using in this tutorial. Tkinter (capital T) is a Python module for creating and displaying graphics and GUIs. It comes built into the 2.6 release, and is a very fun little module.

Alright, let's get to coding
Sure thing. Fist off, open up IDLE.
Before we can do anything, we have to import the Tkinter module. I will be using an unconventional method to import Tkinter.

Code:
from Tkinter import *

As we went over in my last tutorial, modules are just a python file filled with different functions. Using the "from [module] import *" command imports all the functions in [module], instead of just calling them when they are needed. This makes it so we do not have to state that we are using a function from this module before we use it (no module.function() crap, just straight up function() ).
Ok, now that we have our module imported, we can start coding.

Code:
master = Tk()

This just makes it easer on us; now we don't have to state the Tk() function every time, we can just say master. The Tk() function is the main window of our program. You can have other windows (also called widgets) too, but they will be called different things.

Tkinter assigns functions to buttons and other intractable objects. Before we can actually build the GUI, we need to create those functions.

Code:
def text():
    print "You Clicked me!"

def text2():
    print "You Clicked me too!"

Great. Now we have two functions, the text() and the text2().

Now that we have our functions defined, we can actually build the GUI.

Code:
head = Label(master, text="Tkinter Test")
head.pack(side=TOP)

Let's break this code down step by step.
The head = Label part says "hey, i'm making a variable that's containing the function to create a Label". As you can now infer, the function to create text in your GUI is Label(). The actual meat of the Label() function is (master, text="Tkinter Test"). This says "put this text in the "master" window, and make it say "Tkinter Test". The next line actually executes the new function that you assigned to head. It also preforms the pack function on this new variable. Pack just pushes the text to one side of your window. As you can see here, we are pushing it to the TOP. You can also use BOTTOM, LEFT, and RIGHT.

Alright, on to... buttons!
You can create a button in the same way we created that label earlier. You just need to assign the button function to a variable, and then call that variable with a positioning function.

Code:
button1 = Button(master, text="Click me!", fg="red", command=text)
button1.pack(side=LEFT)

Ok, so the function to create a click-able button is... Button()! The juicy part of Button() is (master, text="Click me!", fg="red", command=text). Now again, we are telling Tkinter to create a button in master, and the text inside this button is going to be "Click me!". Now on to fg. fg states the color of the text in the button; you can play around with this until you get a color you like. command=text is the best part. It assigns the button to call the text() command. You don't need the parenthesis's unless you have an argument, but you can include them if you like.
Then, we are just using another pack() function to pack the button to the LEFT.

The next bit of code is just another button:

Code:
button2 = Button(master, text="Click me too!", fg="blue", command=text2)
button2.pack(side=RIGHT)

And we wrap it all up with a

Code:
mainloop()

This is the main loop function of Tkinter, and it insures that the window stays open. You should include it at the end of all your Tkinter programs.


Our Patched-together Code
Ok, after putting this all together, we get:

Code:
from Tkinter import *

master = Tk()

def text():
    print "You Clicked me!"
def text2():
    print "You Clicked me too!"

head = Label(master, text="Tkinter Test")
head.pack(side=TOP)

button1 = Button(master, text="Click me!", fg="red", command=text)
button1.pack(side=LEFT)

button2 = Button(master, text="Click me too!", fg="blue", command=text2)
button2.pack(side=RIGHT)

mainloop()

That's all good fun, but say you wanted user input?
Well, remember how the function for a button was Button()? The function for user input is Entry(). Easy huh?
So our code would look like this:

Code:
enter = Entry(master)
enter.pack(side = RIGHT)

Grabbing the text from an entry box
Ok, so you now have a box were the user can enter text. That's great, but what if you wanted to use that text that the user has entered?
You can make a new function (that means you can make a new button and assign that function to it) and then use the grab command attached to the entry box object.

Code:
def text():
    x = enter.get()
    print x

This code defines a new function. Inside the function, we are doing two things, assigning the variable x to the text inside the entry box we made earlier, and then printing x.

What about pop-up boxes?
I knew it was just a matter of time until you asked about that.
There is a really easy way you can use pop-up boxes in Tkinter; the tkMessageBox module. Yes, tkMessageBox is a septate module from Tkinter. I'm not actually going to go too much into tkMessageBox, because there is already great documentation on it here, and it's a separate module than Tkinter (also, i'm lazy). I'm just going to leave you with a piece of sample code, and i'm going to explain how it works.

Code:
from tkMessageBox import *
showinfo("Title", "Main body text.")

So in this code, we are importing all the functions from tkMessageBox, and then using the function showinfo(). This function will bring up a pop-up box with an OK button and some text. You can give the function two arguments, the first one being a title string, and the second being the actual body string. There are loads of other fun modules in tkMessageBox, such as showwarning(), showerror(), askquestion(), askokcancel(), askyesno(), askretrycancel(), and many more. They all work in relatively the same way as showinfo(). Again, documentation can be found here.

Menu Bars
Menu bars are those little strip of buttons that you see at the top of any program. They usually contain buttons such as "file", "edit", "help", and so on. Tkinter has a built in function for creating these menu bars; it's called the Menu() function.
The argument that goes inside the Menu() function is the window that you want to apply it to; in this case, it's the master window.

Code:
menubar = Menu(master)

As you can see here, I have created a new variable and assigned the Menu() function to it. Now we can go about adding buttons.

Code:
menubar.add_command(label="Save", command=Save)
menubar.add_command(label="Help", command=Help)
menubar.add_command(label="About", command=About)
menubar.add_command(label="Quit", command=master.quit)

In order to add a button to the menu bar, you use add_command().
The arguments that add_command() takes are label=, and command. Label holds the string that you want the actual button to display, and the command points the the command function that you assign earlier in your code.
Now, we are not actually done, we still need to configure the menu to the window.

Code:
master.config(menu=menubar)

Ok, when we throw it all together, we get this.

Code:
menubar = Menu(master)
menubar.add_command(label="Save", command=Save)
menubar.add_command(label="Help", command=Help)
menubar.add_command(label="About", command=About)
menubar.add_command(label="Quit", command=master.quit)
master.config(menu=menubar)

This will give us a nice looking menu bar.

Other Methods for Organizing your GUI
You have seen the pack() function, but this is not the only way to organize your buttons, and other goodies in your GUI. There is also the grid() function. Generally speaking, the grid() function leaves your GUI looking much cleaner than pack() does. Grid() uses rows and columns for organization. Here is an example of using grid():

Code:
lone = Label(master, text="Some Text")
lone.grid(row=0, column=0)

bone = Button(master, text="Button", command=click)
bone.grid(row=0, column=1)

This should make some text and then throw a button in a column to the right of it. As you can see, the grid() function is pretty easy to use.


And that brings the first part of my Tkinter tutorial to an end. I was looking back, and now I realize how long part one is. Part two will go over a lot of the other "widgets" (functions) that Tkinter has to offer. Some of those include Checkbuttons, Labelframes, Scrollbars, Spinboxes, images, and the all mighty canvas.
Thanks for reading, and enjoy Tkinter!
Logged

Check yo dick for the HIV
LOOK!
I'm Owl City!
And i'm totally, 100% hetrosexual!

Pages: [1]
  Print  
 
Jump to: