张仙人

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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)

posted on 2018-03-09 19:38  张仙人  阅读(282)  评论(0编辑  收藏  举报