Getting started with GUIs

So far all the programs I’ve done on here have been decidedly old-school and run in the command line. As I’ve mentioned before, I am learning as I go and I haven’t got very far yet with using GUIs, but I thought I’d do a post that uses the tkinter features of Python to make GUIs.

Here’s what our first GUI will look like. You can move it, resize it, minimise it and click the button (although it doesn’t do anything!).

Here’s the code.

The first line imports the tkinter modules we need. The next lines create a window and give it a size and a title. You can play around with changing these aspects, if you like. We are using a “class” within tkinter here. We’re getting into Object Oriented Programming with this little script. The line: “root = Tk()” makes a new object: an instance of the class “Tk”. We can then use some of the “methods” which that class contains. The method “title” sets the title and “geometry” defines the size.

The dot notation shows us that we are using methods. We have used this type of thing before, for instance, to raise a number to a power we said something like:

i = math.pow(2, 3)

Here the dot notation shows that we are using one of the methods defined in the math module. This one is called “pow” and it raises the first number to the power of the second. An even better example would be when we sorted a list:

mylist.sort()

Here we have created a list (“mylist”) and we use its name followed by “.sort()” to get the list-method “sort” to order our list.

Next we need a “frame” within the window, and a button. The “.grid()” method causes the layout manager to make the items we have created visible.

At the end of the code we start the main loop. This makes the window keep displaying itself on the screen and checking for any action the user might make. You may have seen similar things if you’ve had a go at pygame in which our graphics windows are controlled by a loop which runs continually until we quit the game.

I hope this makes sense! Anyway, the code itself is pretty simple. Look out for more GUI posts!

antiloquax

About these ads

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: