New Required Python Skills: Basics of Tkinter
Resources available for teachers. Get Access
Try out the program above, and then add a second slider to control the speed of the Finch’s right wheel.
By now, you have probably realized that the Finch doesn’t turn off automatically when you close the GUI window. Add a “Quit” button that will turn off the Finch and close the window.
Add three more sliders to your GUI to enable the user to control the red, green, and blue values for the Finch’s beak.
You can even use the Finch as a controller for your own video game! The rest of this lesson will focus on creating a starter program that you can then customize to make your own game.
Start your project by creating a canvas that contains a circle controlled by the Finch.
- Create a Tk window with a canvas. Add a circle to the canvas.
- Create a loop that will update the canvas until the user turns the Finch upside down. When the user turns the Finch upside down, the program should end.
- Within the update loop, set the x-coordinate of the circle using the y-acceleration of the Finch. For example, this line of code sets the coordinates of ball1 based on the y-acceleration y . The constants are determined by the size of the canvas and the circle, so you may need to modify those (it may be a good idea to use variables for the center of the canvas and the radius of the circle!).
- Modify your call to .coords() so that you also set the y-coordinate of the circle using the x-acceleration of the Finch.
- Now you should be able to move the circle around the screen by tilting the Finch in different directions!
Now that you can use the Finch to control one circle on the screen, add a second one that moves randomly.
- Create a second circle with a different color.
- The second circle will move to a new position every 3 seconds.
- Use time.time() to initialize a variable startTime outside your update loop.
- Within the update loop, move the second circle to a new random position if more than three seconds have elapsed since startTime. Then update startTime by setting it equal to the current system time.
Now you can use the first circle to chase the second circle around the screen. Starting from this simple game, create your own game with Tkinter and the Finch! You can be as creative as you like, but if you need a starting point, consider the following:
- How can you keep score?
- How can you make the Finch-controlled circle move more smoothly?
- How can you incorporate an “enemy” into the game?
- How can you incorporate more graphics and sound into the game?