Creating a Simple GUI in Python
This tutorial is going to be on how to create a GUI in Python using Tkinter.
Tkinter is a basic package to give your projects a simple GUI with the essential GUI elements such as textboxes, checkboxes, buttons and more.
Our program is going to be a simple program where the user enters text in to a textbox, then clicks a button to get it output to the console. Simple but it helps you to understand the concepts.
First we need to get the Tkinter package by importing it all (* = all/everything)...
- from tkinter import *;
Now we are going to create a class to hold our application, named Application appropriately. It takes the parameter of Frame as it's master where it binds to.
- class Application(Frame):
- def __init__(self, master):
- super(Application, self).__init__(master);
The above code also create the init method ran on the creation of the Application class. It essentially sets the application frame up, sets it to a grid view then runs a method named widgets.
Next we need to set the widgets function definition...
- def widgets(self):
- Label(self, text="Enter the text below...").grid(row=0,column=0,sticky=W);
- self.textBox = Entry(self);
- Button(self, text="Output!", command=self.runText).grid(row=2,column=0,sticky=W);
This does the following...
Creates a label with the instructions text and places it in the upper left hand corner of the GUI frame using the grid method.
Creates a textbox (Entry - a single lined textbox) and places it below the label. It sets it to the self.textBox variable.
Creates a button with the command set to runText which is another function we are going to create - so it runs our function once the button is clicked. Again, this button is placed below the textbox/Entry box.
Because the Label and Button objects are not set to a variable, we are unable to alter them once they are created - this saves memory within our program, and space.
Each of the objects take the first, required parameter of the application frame it will bind on to, which is self because we are within the Application class. It then takes special parameters for it's objects purpose (text, command, etc.).
Finally we need to create the runText function which simply prints the text returned by the get method of the textbox on self.textBox...
- def runText(self):
The TK Root:
Finally (outside of the application class, at zero indentation), we create a Tk/Tkinter variable named root, set it's title and size/geometry, create an Application class instance named 'app' with the Frame parameter set to the Tkinter root variable, and run the mainloop of root...
- root = Tk();
- root.title("First GUI!");
- app = Application(root);