Tkinter Canvas Build racket
First create a static racket, at this point you can create the Racket class, in which we set its initial size and position.
Example#1
Add the racket design, where the racket class is added first. In this class, the size and color of the racket is designed in row 29 and the position of the initial racket is set in row 30.
from tkinter import *
from random import *
import time
class Ball:#class Ball():#Written like this is the same
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 the initial position of the ball
startPos = [-4, -3, -2, -1, 1, 2, 3, 4] # random number of initial x-axis movements of the ball
shuffle(startPos) # upset the ordering
self.x = startPos[0] # initial horizontal movement of the ball in units
self.y = step # vertical units of movement
def ballMove(self):
self.canvas.move(self.id, self.x, self.y) # step is positive for downward movement
ballPos = self.canvas.coords(self.id)
if ballPos[0] <= 0: # detect if the ball is over the left side of the canvas
self.x = step
if ballPos[1] <= 0: # detect if the ball is over the top of the canvas
self.y = step
if ballPos[2] >= winW: # detect if the ball goes over the right side of the canvas
self.x = -step
if ballPos[3] >= winH: # detect if the ball is over the bottom of the canvas
self.y = -step
class Racket():
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0,0,100,15,fill=color) # racket object
self.canvas.move(self.id, 270, 400)
winW = 640 # Define the width of the canvas
winH = 480 # Define the height of the canvas
step = 3 # Define the velocity think of it as a displacement step
speed = 0.03 # Set the speed of movement
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 a canvas
canvas.pack()
tk.update()
ball = Ball(canvas,'yellow',winW,winH) # Define the ball object
racket = Racket(canvas,'purple') # Define the purple racket
while True:
ball.ballMove()
tk.update()
time.sleep(speed) # You can control the speed of movement
# tk.mainloop()
Output: