tkinter 製作屏保
阿新 • • 發佈:2019-01-01
import random import tkinter class RandomBall(): ''' 定義球的類 ''' def __init__(self, canvas, scrnwidth, scrnheight): #canvas:畫布 self.canvas = canvas #圓心座標 self.xpos = random.randint(10, int(scrnwidth)-20) self.ypos = random.randint(10, int(scrnheight)-20) #球的速度,分速度為2個軸 self.xvelocity = random.randint(2, 5) self.yvelocity = random.randint(2, 5) #半徑 self.radius = random.randint(20, 120) #顏色RGB c = lambda: random.randint(0, 255) self.color = '#%02x%02x%02x'%(c(), c(), c()) #螢幕長寬 self.scrnwidth = scrnheight self.scrnheight = scrnheight #在畫布上畫球 def create_ball(self): x1 = self.xpos - self.radius y1 = self.ypos + self.radius x2 = self.xpos + self.radius y2 = self.ypos - self.radius self.item = self.canvas.create_oval(x1, y1, x2, y2, fill=self.color, outline=self.color) #球的移動 def move_ball(self): self.xpos += self.xvelocity self.ypos += self.yvelocity #球碰到螢幕邊緣彈回 if self.xpos + self.radius >= self.scrnwidth\ or self.xpos + self.radius <= 20: self.xvelocity = -self.xvelocity if self.ypos + self.radius >= self.scrnheight\ or self.ypos + self.radius <= 20: self.yvelocity = -self.yvelocity #球的移動函式,就是移動複製 self.canvas.move(self.item, self.xvelocity, self.yvelocity) class ScreenSanver(): ''' 定義屏保 ''' def __init__(self): #把N個球放在佇列中 self.balls = [] #球的數量 self.num_balls = random.randint(6, 20) #生成框架 self.root = tkinter.Tk() #取消邊框 self.root.overrideredirect(1) #製作透明視窗 self.root.attributes('-alpha', 0.3) #任何滑鼠移動都退出屏保 self.root.bind('<Motion>', self.myquit) #任何鍵盤動作都可以退出屏保 self.root.bind('<Key>', self.myquit) #得到螢幕大小規格 w, h = self.root.winfo_screenwidth(), self.root.winfo_screenheight() #建立畫布 self.canvas = tkinter.Canvas(self.root, width=w, height=h) self.canvas.pack() #畫布上畫球 for i in range(self.num_balls): ball = RandomBall(self.canvas, scrnwidth=w, scrnheight=h) ball.create_ball() self.balls.append(ball) self.run_screen_saver() self.root.mainloop() #球的運動函式 def run_screen_saver(self): for ball in self.balls: ball.move_ball() self.canvas.after(20, self.run_screen_saver) #解構函式 def myquit(self, e): self.root.destroy() if __name__ == "__main__": ScreenSanver()