Start letting the ball bounce back and forth in the vertical direction of the canvas.
from tkinter import *import randomimport time# Create Ball class class ball: def __init__ (Self,canvas,color): #初始化函数, including canvas and color parameters self.canvas = canvas #把参数canvas赋值给对象变量canvas self.id = canvas.create_oval (10,10,25,25,fill=color) #创建椭圆, Upper-left and lower-right XY coordinates, returning id representing the graphic Self.canvas.move (self.id,245,100) #把画好的椭圆形移动的画布中心, graphical ID representation self.x = 0 #对象变量x就是水平移动的初始值, equivalent to not moving, called in the paint function below self.y = -1 # The object variable y is the initial value of the vertical movement, which is equivalent to moving up, in the drawing function belowWith self.canvas_height = self.canvas.winfo_height () #获取画布的高度, the height of the canvas is measured from top to bottom Def draw (self): #定义画图动作 self.canvas.move (SELF.ID,SELF.X,SELF.Y) #按照x和y定义的步长来移动小球 pos = self.canvas.coords (self.id) &NBSP;&NBSP;&NBSP;&NBsp; #coords函数通过id返回画布上画好东西的xy坐标值 if pos[1] <= 0: # POS Returns a list [X1,y1,x2,y2] that represents the XY coordinates of the upper-left and lower-right corners of the ellipse, respectively self.y = 1 #当球左上角y1坐标小于等于0, The description touches the top of the canvas, re-sets the object variable y to 1, and starts to move vertically downward if pos[3] >= self.canvas_height: #当球右下角y2坐标超过画布高度, reset the object variable y to-1 and start moving vertically up self.y = -1 #创建游戏的桌布tk = tk () # Create a Tk object with the TK () class, which is a basic window on which you can add something else tk.title ("Game") #给Tk对象窗口加一个标题tk. Resizable (0,0) #tk窗口大小不可调整tk. Wm_attributes ("-topmost", 1) # Tell Tkinter to put the window on the front Canvas = canvas (tk,width=500,heigh=400,bd=0,highlightthickness=0) #Canvas是一个画布类canvas. Pack () &NBSP;&NBSP;&Nbsp; # Adjusts its own size according to the width height parameter specified in the previous line tk.update () #画一个红色的球ball = ball (canvas, ' red ') #用Ball类在画布上画一个红色的球 # main loop, let Tkinter constantly repaint the screen While 1: ball.draw () #调用Ball类的作画函数 Tk.update_idletasks () #updata_idletasks和updata这两个命令 tk.update () #让tkinter快一点把画布上的东西画出来 time.sleep (0.01) #延时让动画效果慢一点
The third stage of the fun Learning Python pinball game