Tkinter Canvas Design the ball to move down
Define the name of the canvas window as Bouncing Ball, and define the width and height of the canvas as 640 pixels and 480 pixels respectively. The ball will move down and disappear, and will disappear when it goes beyond the canvas.
from tkinter import *
from random import *
import time
class Ball:#class Ball():#It is written the same way
def __init__(self,canvas,color,winW,winH):
self.canvas = canvas
self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # Create ball object
self.canvas.move(self.id,winW/2,winH/2) # Set initial ball position
def ballMove(self):
self.canvas.move(self.id, 0, step) # step is a positive value indicating a downward movement
winW = 640 # Define canvas width
winH = 480 # Define the canvas height
step = 3 # Defining velocity can be thought of as a displacement step
speed = 0.03 # Set movement speed
tk = Tk()
tk.title("Bouncing Ball - apidemos") # Game window title
tk.wm_attributes('-topmost',1) # Make sure the game window is at the top of the screen
canvas = Canvas(tk,width=winW, height=winH) # Create canvas
canvas.pack()
tk.update()
ball = Ball(canvas,'yellow',winW,winH) # Defining the ball object
while True:
ball.ballMove()
tk.update()
time.sleep(speed) # Can control the speed of movement
# tk.mainloop()
Output:
This program is an infinite loop (lines 28 to 31), so we will see an error message in the Python Shell window when we force the canvas window to close, and the example at the end of this chapter will improve the program. The whole program can control the speed of the ball movement using the step size of each ball movement (16 lines) and the speed value of the time.sleep(speed) instruction on line 31 of the loop.
The above program creates the Ball category, which is in the __init__()
method, creates the ball object on line 9, and sets the ball to be approximately in the middle first on line 10. In addition, the ballMove( ) method is created, and this method will move according to the step variable, in this case down each time.