Bouncing Ball Games
To develop a game of bouncing balls and rackets, start by creating a canvas and a pinball ball.
From Tkinter import* import random Import time # Create ball class Ball:def __init__ (self,canvas,color): Self.canva
s = Canvas self.id = canvas.create_oval (10,10,25,25,fill = color) self.canvas.move (self.id,245,100) Starts = [ -3,-2,-1,1,2,3] Random.shuffle (starts) # Random.shuffle () function to disrupt the order of the starts to ensure that each start is a different direction self.x = Starts[0] Self.y =-3 # x and y control the distance and direction of the ball movement Self.canvas_height = self.canvas.winfo_height () # Call Winfo_heigh t function to get the height of the canvas self.canvas_width = Self.canvas.winfo_width () def draw (self): Self.canvas.move (Self.id,sel F.X,SELF.Y) pos = Self.canvas.coords (self.id) # coords function returns a list of four digits representing the coordinates (that is, the upper-left corner (x,y) and the lower right corner (x,y)) if POS[1] &l t;= 0:self.y = 3 if pos[3] >= self.canvas_height:self.y =-3 if pos[0] <=
0:self.x = 3 if pos[2] >=self.canvas_width:self.x =-3 # Absolute value is 3 in order to ensure the speed of the ball in all directions consistent #画布 tk = TK () tk.title ("Game") # defines the canvas window's title tk.resizable (0,0) # to make the size of the window not adjustable. The parameter (0,0) means that the tk.wm_attributes ("-topmost", 1) is not changed in both horizontal and vertical directions to tell Tkinter to place the canvas window before all other windows canvas = Canvas (tk,width = 500, Height = 400,bd = 0,highlightthickness = 0) # BD and highlightthickness ensure that there are no borders outside the canvas canvas.pack () tk.update () # Let the canvas initialize ball = B All (canvas, ' red ') while 1:ball.draw () Tk.update_idletasks () tk.update () # Update_idletaske and update commands let Tkinter quickly
Quick Repaint Screen Time.sleep (0.01)