This code is windows-specific. It will not run on linux (I’ve tried).
Make sure you have python and tkinter installed. Test if tkinter is installed with python -m tkinter. It should open a demo window. If not, you may have to run the python installer again and make sure you have the “install tkinter/IDLE” box checked.
imports
We will only need 2 imports. tkinter is python’s standard GUI toolkit, which we’ll use for drawing the window.
This is not an in-depth tkinter tutorial, so refer to the tkinter documentation if you really want to understand what the code does.
desktop pet
we’ll create a class for our pet
In it’s constructor (__init__), we’ll set up the window and use a placeholder image.
Then we’ll write a method that will be called continuously once the mainloop starts (it doesn’t have to be called update).
Calling .after() on our window does not by itself cause the function to be called in a loop. To achieve this, we must have the method call itself the same way.
Finally, we’ll call the constructor
If you run the code now, and put an image named “placeholder.png” in your folder (such as the stickman here), you should have your character appear in the top left of your screen.
Next let’s make the character move.
making the character move
We’ll want to keep track of the character’s x position and draw him there.
Replace the call to self.window.geometry() with this:
…and fill in the update() method:
To move the character, we call self.window.geometry() and fill in our new x position.
We will again have to call self.label.pack().
If you run the code now, the character should move to the right.
He’s not animated yet, so let’s do that next.
animating the character
You can use this terrible walking animation I made if you don’t have one yet.
Replace the call to tk.PhotoImage() in the constructor with the gif:
This line uses a list comprehension
to create a list, where every element is the result of calling tk.PhotoImage(), with a different index
to select each frame of the gif. If your gif has a different amount of frames, you’ll need change the range() call.
We’ll want to keep track of the index of the current frame and assign the frame to a variable.
We’ll also want to keep track of how much time has passed since the frame has advanced.
Lastly, replace the whole update method with this one:
Here we check if 50ms have passed since we last advanced the frame and only advance it then.
To keep our frame index within the bounds of the amount of frames we have, we use the modulo (%)
operator to get the remainder of an integer division by the number of frames (the length of our array that
contains the frames).
Our character should now move right and be animated! From here, it’s up to you to add more logic.
Here are some ideas: