最近老师在讲 tkinter,所以我做了一个抽奖小游戏。
一、效果图
先上效果图。红色的小球会围绕蓝色小球做环形运动。我设置的四个角是奖品,其余的都是再接再厉。
二、方法
基于tkinter中的button,text,PIL ,time.Canvas
drawPath():用于画蓝色的小球
Ball类 初始化画布、运动小球大小、运动的起点。
ball类-》draw() 控制小球的运动。这里用到一个方法叫canvas.coords。这个方法可以获取运动小球当前在画布上的坐标。并返回一个数组。比如 pos=self.canvas.coords 。左边:pos[0],右边pos[2],上边:pos[1],下边:pos[3].用if和pos 可以控制小球的上下左右运动。
self.canvas.move(self.id,self.x,self.y)
#获取某个对象在画布的坐标,返回一个数组(两个坐标,左上角的坐标和右下角的两个坐标)
pos = self.canvas.coords(self.id)
getNowPoint(pos[0],pos[1],pos[2],pos[3])
#打印获取的坐标
#如果最上面的纵轴坐标在顶上,则往下移动一个像素
if pos[1] <=30 and self.y==-80:
self.x = 80
self.y=0
print("pos1" + str(self.x) + ":pos1:" + str(self.y))
#如果最下面的纵轴坐标在底上,则向左移动
elif pos[3] > 300 and self.x==0 and self.y==80:
self.x = -80
self.y=0
print("pos3" + str(self.x) + ":pos3:" + str(self.y))
#宽度控制#
#如果在左边框了,那么向右边移动3像素
elif pos[0] <30 and self.x== -80:
self.x = 0
self.y= -80
print("pos0" + str(self.x) + ":pos0:" + str(self.y))
#如果到右边框了,左移动3像素
elif pos[2] > 300 and self.y==0:
self.x = 0
self.y=80
print("pos2:" + str(self.x) + "pos2:" + str(self.y))
getNowPoint()当前红色运动小球的位置。