graphical user interfaces hello world

GRAPHICAL USER INTERFACES ­ HELLO WORLD
GUI stands for Graphical User Interface. A GUI is the window that a user interacts with, by using
buttons, icons, text boxes, etc.
Exercise:
We’re going to make our first GUI. It should look like this:
(note: it will look slightly different if you are using Microsoft Windows)
We’re going to be using Tkinter, which is Python’s default GUI toolkit.
Open a new script. At the top of the file, we have to import Tkinter, and the tkMessageBox.
import * means import everything from this library. Add these two lines:
from Tkinter import *
from tkMessageBox import *
Now we’re going to define a class. A class is like a blueprint or a template; we can create as
many instances of a class as we like. This class contains all the user interface components that
our application will use. We’re going to name our class “HelloInput”. Add the following line to your
code:
class HelloInput:
Now we’re going to make an __init__ function. This contains all the information Python needs to
run when we make an instance of the class. Add the following line, and make sure that it is
indented:
def __init__(self, parent):
Now we’re going to create the two buttons: Hello and Quit. We give them a label, and a
command to execute when they are clicked. Hello will call the say_hi function, and Quit will
destroy the window. We then add the buttons to a grid, which defines how they are arranged in
the window. Add the following lines, and make sure they are indented (so they are inside the
__init__ function:
self.hello_button = Button(parent, text=”Hello”, command=self.say_hi)
self.hello_button.grid(column = 2, row = 0)
self.quit_button = button(parent, text=“Quit”, command=parent.destroy)
self.quit_button.grid(column = 3, row = 0)
Now we’re going to make the input field and the label “Enter your name”. Add these lines:
self.input = Entry(parent)
self.input.grid(column = 1, row = 0)
self.label = Label(parent, text = ”Enter your name: ”)
self.label.grid(column = 0, row = 0)
Now we’re going to make the function that will be called when the user clicks Hello. It will create
a message box that greets the user. Add the following lines, and make sure the first line is
formatted to be in line with def __init__
def say_hi(self):
showinfo(message = “Hi there “ + self.input.get())
Finally, we have to add four lines that create a root window, an event loop, create the instance of
the class, and give the window a name. Put these lines at the bottom of your file:
root = Tk()
root.wm_title(“Hello, World!”)
app = HelloInput(root)
root.mainloop()
Now save your file as helloworld.py and run!