from tkinter import *
import random
import time
class Ball:
def __init__(self,canvas,color):#初始化函数,画布和颜色
self.canvas = 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)#打乱
self.x=starts[0]
self.y=-3
self.canvas_height=self.canvas.winfo_height()#获取画布当前高度并赋值
self.canvas_width=self.canvas.winfo_width()
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id)#获取当前对象的坐标
if pos[1]<=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
tk=Tk()
tk.title("Game")
tk.resizable(0,0)#使窗口大小固定
tk.wm_attributes("-topmost",1)#窗口置顶
canvas=Canvas(tk,width=500,height=400,bd=0,highlightthickness=0)#无框画布
canvas.pack()
tk.update()
ball=Ball(canvas,'red')
while 1:
ball.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)