预览图
源码
import tkinter
import random
import operator
from PIL import Image, ImageTk
class Ball():
def __init__(self, canvas, scrwidth, scrheight):
self.canvas = canvas
self.scrwidth = scrwidth
self.scrheight = scrheight
self.posx = random.randint(0, self.scrwidth-100)
self.posy = random.randint(0, self.scrheight-100)
self.x_vel = random.randint(10, 25)
self.y_vel = random.randint(10, 25)
self.radius = random.randint(2, 10)
self.ball_color = lambda: random.randint(0, 255)
self.color = '#%02x%02x%02x' % (self.ball_color(), self.ball_color(), self.ball_color())
def creat_ball(self):
x1 = self.posx - self.radius
y1 = self.posy - self.radius
x2 = self.posx + self.radius
y2 = self.posy + self.radius
self.round_ball = self.canvas.create_oval(x1, y1, x2, y2, fill = self.color, outline = self.color)
def move_ball(self):
self.posx += self.x_vel
self.posy += self.y_vel
right1 = self.posx + self.radius >= self.scrwidth
under = self.posy + self.radius >= self.scrheight
left = self.posx - self.radius - 40 <= 0
top = self.posy - self.radius - 40 <= 0
if right1:
self.x_vel *= -1
if under:
self.y_vel *= -1
elif under:
self.y_vel *= -1
elif left:
self.x_vel *= -1
if top:
self.y_vel *= -1
elif top:
self.y_vel *= -1
else: pass
self.canvas.move(self.round_ball, self.x_vel, self.y_vel)
class Screen(Ball):
def __init__(self):
self.ball = list()
self.ball_num = random.randint(100, 200)
self.base = tkinter.Tk()
self.base.overrideredirect(1)
width = 1920
height = 1080
self.canvas = tkinter.Canvas(self.base, width = width, height = height)
self.canvas.pack()
images = ImageTk.PhotoImage(Image.open("img1.jpg"))
self.canvas.create_image(960, 540, image = images)
super().__init__(self.canvas, width, height)
x = y = 0
for i in range(self.ball_num):
new_ball = Ball(self.canvas, width, height)
new_ball.creat_ball()
self.ball.append(new_ball)
if x == new_ball.posx:
new_ball.ball_color = lambda: random.randint(0, 255)
if y == self.posy:
new_ball.ball_color = lambda: random.randint(0, 255)
x = new_ball.posx
y = new_ball.posy
self.run_ball()
self.bind()
self.base.mainloop()
def run_ball(self):
for ball in self.ball:
ball.move_ball()
self.canvas.after(200, self.run_ball)
def bind(self):
self.base.bind('<Motion>', self.myquit)
def myquit(self, quit):
self.base.destroy()
if __name__ == "__main__":
while not Screen():
pass