本文實例為大家分享了python利用tkinter實現屏保的具體代碼,供大家參考,具體內容如下
import random
import tkinter
class RandomBall():
'''
運動的球
'''
def __init__(self, canvas, scrn_width,scrn_heigh):
'''
球的構造函數
:param canvas: 傳入畫布,在畫布上進行球的構造
:param scrn_width: 傳入屏幕寬度
:param scrn_heigh: 傳入屏幕高度
'''
#x,y表示出現的球的圓心
self.ball_x = random.randint(20, int(scrn_width - 20)) #球出現的隨機x坐標
self.ball_y = random.randint(10, int(scrn_heigh - 10)) #球出現的隨機y坐標
#模擬運動:就是不斷地重畫球,不斷地更新球的位置
self.x_move = random.randint(4, 30) #模擬x方向運動
self.y_move = random.randint(5, 20) #模擬y方向運動
#定義寬度和高度和畫布
self.canvas = canvas
self.scrn_width = scrn_width
self.scrn_heigh = scrn_heigh
#球的大小隨機
self.rad = random.randint(20, 150) #用半徑rad表示球的大小
#定義顏色
c = lambda : random.randint(0, 255)
self.color = "#%02x%02x%02x"%(c(), c(), c())
def creat_ball(self):
'''
用構造函數中的值創建一個球
:return:
'''
#tkinter沒有畫圓函數,只有橢圓函數
#但在正方形里面畫的橢圓就是正圓
#已知圓心坐標和半徑,則圓心坐標減半徑能求出正方形左上角
#圓心坐標加上半徑,能求出右下角
#已知左上角和右上角,可以畫出
x1 = self.ball_x - self.rad #左上角的x坐標
y1 = self.ball_y - self.rad #左上角的y坐標
x2 = self.ball_x + self.rad #右下角的x坐標
y2 = self.ball_y + self.rad #右下角的y坐標
#在有對角坐標的情況下就可以創建圓
self.item = self.canvas.create_oval(x1, y1, x2, y2, fill = self.color, outline = self.color)
# 球動
def move_ball(self):
self.ball_x += self.x_move #球移動后的新x坐標
self.ball_y += self.y_move #球移動后的新y坐標
# 碰壁回彈判斷
if self.ball_x + self.rad >= self.scrn_width: #撞到了右邊的墻
self.x_move = -self.x_move
if self.ball_x - self.rad <= 0: #撞到了左邊的墻
self.x_move = -self.x_move
if self.ball_y + self.rad >= self.scrn_heigh: #撞到下面的墻
self.y_move = -self.y_move
if self.ball_y - self.rad <= 0: #撞到上面的墻
self.y_move = -self.y_move
self.canvas.move(self.item, self.x_move, self.y_move) #利用x,y的移動距離控制球的移動快慢
class ScreenSaver():
'''
可以被啟動的屏保
'''
#創建一個list裝創建的球
def __init__(self):
self.balls = list()
self.nums_balls = random.randint(6, 20) #產生隨機數量的球
self.baseFrame = tkinter.Tk() #啟動界面
self.baseFrame.overrideredirect(1) #取消邊框
#移動鼠標則退出屏保
self.baseFrame.bind("
", self.my_quit)
self.baseFrame.attributes('-alpha', 1)
#鍵盤任意鍵退出屏保
self.baseFrame.bind("
",self.my_quit)
#得到屏幕的寬和高
w = self.baseFrame.winfo_screenwidth()
h = self.baseFrame.winfo_screenheight()
#創建畫布
self.canvas = tkinter.Canvas(self.baseFrame, width = w, height = h)
self.canvas.pack()
#在畫布上畫球
for i in range(self.nums_balls):
ball = RandomBall(self.canvas, scrn_width = w, scrn_heigh = h)
ball.creat_ball()
self.balls.append(ball)
self.run_screen_saver()
self.baseFrame.mainloop()
#球動函數
def run_screen_saver(self):
for ball in self.balls:
ball.move_ball()
#在sleep100ms以后啟動第二個參數函數,相當于100ms動一次
self.canvas.after(100, self.run_screen_saver)
#當事件發生時,傳入event,退出屏保
def my_quit(self, event):
#析構(退出)屏保
self.baseFrame.destroy()
if __name__ == "__main__":
#啟動屏保
ScreenSaver()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

