Python tkinter實現(xiàn)的圖片移動碰撞動畫效果【附源碼下載】
更新時間:2018年01月04日 14:48:58 作者:chengqiuming
這篇文章主要介紹了Python tkinter實現(xiàn)的圖片移動碰撞動畫效果,涉及Python tkinter模塊操作圖片基于坐標動態(tài)變換與數(shù)值判定實現(xiàn)移動、碰撞檢測等相關操作技巧,需要的朋友可以參考下
本文實例講述了Python tkinter實現(xiàn)的圖片移動碰撞動畫效果。分享給大家供大家參考,具體如下:
先來看看運行效果:
具體代碼如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import time try: from tkinter import * except ImportError: #Python 2.x PythonVersion = 2 from Tkinter import * from tkFont import Font from ttk import * from tkMessageBox import * import tkFileDialog else: #Python 3.x PythonVersion = 3 from tkinter.font import Font from tkinter.ttk import * from tkinter.messagebox import * # 配置 # 要打開的圖像 image1 = "open.gif" # 初始坐標 x0 = 50.0 y0 = 50.0 # 列表將包含所有的x和y坐標.到目前為止,他們只包含初始坐標 x = [x0] y = [y0] # 每次移動的速度或距離 vx = 1.0# x 速度 vy = 0.5# y 速度 # 邊界,這里要考慮到圖片的大小,要預留一半的長和寬 x_min = 46.0 y_min = 46.0 x_max = 754.0 y_max = 554.0 # 圖片間隔時間,要動畫效果,此處設為每秒40幀 sleep_time = 0.025 # 運行步數(shù) range_min = 1 range_max = 2000 # 創(chuàng)建500次的x和y坐標 for t in range(range_min, range_max): # 新坐標等于舊坐標加每次移動的距離 new_x = x[t - 1] + vx new_y = y[t - 1] + vy # 如果已經(jīng)越過邊界,反轉方向 if new_x >= x_max or new_x <= x_min: vx = vx * -1.0 if new_y >= y_max or new_y <= y_min: vy = vy * -1.0 # 添加新的值到列表 x.append(new_x) y.append(new_y) # 開始使用tk繪圖 root = Tk() root.title("腳本之家 tkinter動畫測試") #在這里修改窗口的標題 canvas = Canvas(width=800, height=600, bg='white') canvas.pack() photo1 = PhotoImage(file=image1) width1 = photo1.width() height1 = photo1.height() image_x = (width1) / 2.0 image_y = (height1) / 2.0 # 每次的移動 for t in range(range_min, range_max): canvas.create_image(x[t], y[t], image=photo1, tag="pic") canvas.update() # 暫停0.05妙,然后刪除圖像 time.sleep(sleep_time) canvas.delete("pic") root.mainloop()
附:完整實例代碼點擊此處本站下載。
注:tkinter只能識別gif格式圖片,將jpg或png格式圖片后綴名簡單改成gif是不能識別的!
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python scikit-learn 做線性回歸的示例代碼
本篇文章主要介紹了Python scikit-learn 做線性回歸的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11Python3中延時變量和 free_list鏈表的區(qū)別解析
這篇文章主要介紹了Python3中延時變量和 free_list鏈表的區(qū)別,在Python3中,"延時變量" 和 "free_list鏈表" 是兩個不同的概念,他們之間沒有直接聯(lián)系,本文給實例相結合給大家講解的非常詳細,需要的朋友可以參考下2023-04-04