Monday, 26 May 2014

Tkinter - Python games with Tkinter

Note: I would only use Tkinter to create games if you have an issue installing external python libraries to your system or if you're using Python 3 rather than Python 2. Otherwise the specific game libraries pygame or pyglt are both superior and easier to learn. There are introductory tutorials to both of these in the sidebar.

Why Tkinter and what is it?


Tkinter is a python library that comes standard with both Python 2 and Python 3 for generating Graphical user interfaces (GUIs). It's ubiquity is its strength more than anything else and I frequently resort to Tkinter when I can't get other libraries installed (a common problem for many Digital Technology classes here in NZ).

Making windows and objects


Open IDLE (if you don’t have it download and install it from here - you want the Python 3.4.0), select a ‘New File’ from the file menu. This is where we will write the majority of our code. the other window is called a ‘shell’ and allows you to interact with your program - but it will make things more complicated than they need to be so we’ll leave it alone for now.

If this is your first time programming - here are 4 things to know:

    1) spelling and capitalization are crucially important. If your code doesn’t work check your spelling

    2) in python, indentation is important. Code from this tut should be copied directly with indents preserved. If your code doesn’t work, check your indents are right.

    3) Patience. You will make mistakes. Lots of them. They will irritate you. You will stop making them, but only through practice. If you’re getting irritated stop and try something else for a while!

    4) Google it. Seriously. Any problem you have - google it and pick the result (look for a website called stack overflow) and chances are you will find a solution.

Get started - make a window

Copy and paste the following code into the window:


Then select ‘Run’ from the file menu above or push F5 on your keyboard (or fn and F5 on OSX). If you get an import error (i.e. your console says something like 'cannot find Tkinter module') try changing the import statement from import Tkinter (for Python 2.7) to import tkinter (Python3)

You made a window!

Filling the window 

Try replacing your code with this instead, and hit Run. Time for a bit of explanation!

You’re doing several things:
    creating a window:
                         Window = Tk()

    filling the window with something you can draw on:
                         canvas = Canvas(height=500, width=500, bg='red')
                         canvas.pack()

    creating a rectangle in that canvas:
                        canvas.create_rectangle(200,200,300,300, fill='blue', activefill='green') #x1,y1,x2,y2
                       (N.B. you can make lots of other shapes using: create_oval, create_arc, create_line etc)

    then running our program:

                         Window.mainloop()

If you care about any of this (or want to know more!) - just ask Elf google it.

Good news: you don’t need to understand it to use it!



CHALLENGE #1!


Make a 400x 400 pixel window with a green background that has a smiley face on it.

Adding images


Find an image from somewhere that is in .gif format (or find an online converter). Put it in the same directory as where your python file is saved and give it the name ‘image.gif’

Now try this code:




What do you need to change to move your image around your canvas?



Duplicates


OK now we’re going to do some more advanced programming. Why? Because we want lots of images in lots of places rather than just one. We’re going to use a loop to do that (specifically a for loop). Here’s your code:


Random


Now to explain that ‘import’ statement up the top. When programming it’s common to use bits of code other people have made. These are called libraries and we’re already using one called Tkinter. Now we need to use another one called random which will allow us to generate random numbers (yes exactly like playing calculator cricket). Try this:





and now your images are randomly located all over the map :) Note that we’ve also slightly changed our for loop.

CHALLENGE #2!


Make 20 ovals of random sizes and locations all over your canvas

Movement!


So random placement is ok - but movement would be better. To start we’re going back to moving one image at a time in the interest of simplicity. We’re going to do this by DEFINING two VARIABLEs for the position of our image. Then we’re going to re-draw our image each time it moves and updates our canvas.



Advanced movement


So moving things is ok - but when really want them to move forever, not just for a set period of time. For this we will need a new structure called a while loop.



Boundaries


Now we can add another kind of programming tool called an if statement (or a conditional statement). These allow us to specify different actions depending on what’s going on! Try this:





Whoa?! That’s a bunch of new code. All it’s doing is saying that whenever your object gets to the edges of our window we change it’s speed. See if you can follow through the logic (but again don’t worry if you can’t). To give you a clue - the x and y are position VARIABLES (they remember where on the screen our object is) and the dx and dy are how fast to move in either the left or right direction or the up and down direction respectively.

Keyboard control!


To really make this a game though we want you to be able to control aspect of your character with either the mouse or keyboard. We’re going to do this by making the up arrow on the keyboard make the object move faster and the down key do the opposite.

Try it out. What do you notice? Can you find the bug?

Once again - if this doesn't work and your error message say something about '<key>' in the .bind() command above change <key> to <Key> and it should work.

We’ve used a heap more code this time and something called a ‘method’. It’s quite a bit more complicated and so once again - if you don’t understand don’t worry! However, the bad news is that we’ve reached the limit of what we can do programming as we have been. To go further we’re going to have to think about our programs in a way called ‘Object Oriented Programming’. Think about it like this: in our example above we keep variables for the speed and position of our character. If we had multiple characters we would have to make all these again for all of them and the number would quickly become unmanageable (so would the code for that matter!) - so we need a new way of thinking about things. We will do this by creating objects and getting each object to remember its own speed and position.

From here you have a few choices - continue with the more complicated programming (which will be useful for any language or game you use in the future), move onto something else like unity or blender, or spend some time designing your game and use what you’ve learned above to make a randomly generated background.



 

No comments:

Post a Comment