微信跳一跳自動代碼,具體內容如下
那個跳一跳python,有幾個python文件,其中有一個是得到截圖,然后鼠標在圖片上點擊兩次,python窗口上會打印兩次鼠標的位置,并且會跟上一行這兩個點之間的距離。
這個功能我先給除去獲取截屏,就說怎么在某張圖片上算出兩次點擊的距離。
首先,需要用到圖形模塊,PIL:
from PIL import Imageimg = Image.open('0.jpg')
然后用圖形繪制模塊matplotlib來給出一個plot對象:
import matplotlib.pyplot as pltfig = plt.figure()
給這個對象加上剛剛打開圖片的標簽:
plt.imshow(img, animated = True)
然后用matplotlib的canvas.mpl_connect函數,將我們點擊的動作和圖片連接起來,這個函數的第二個參數要我們自己的寫。
fig.canvas.mpl_connect('button_press_event', on_press)
在這個自定義的on_press函數,我們要實現得到兩個點以后再算出距離。
那么我們就要有變量來儲存兩個點,臨時儲存點,來計算點擊了多少次,橫縱坐標
分別用全局變量cor=[0,0],coords=[], click_count=0,ix,iy
global ix,iy global click_count global cor ix,iy = event.xdata, event.ydata coords = [] coords.append((ix,iy)) print("now = ", coords) cor.append(coords) click_count += 1
先把點儲存在臨時的coords里面,打印出當前位置,然后將臨時的放入全局變量cor里面, 并且點擊次數+1.
if click_count > 1: click_count = 0 cor1 = cor.pop() cor2 = cor.pop() distance = (cor1[0][0] - cor2[0][0]) **2 + (cor1[0][1] - cor2[0][1]) **2 distance = distance ** 0.5 print("distance = ", distance)
當點擊次數大于1的時候,就說明已經儲存了兩個點了。
這里用的棧pop()方法得到兩個點,分別放入cor1 和 cor2, 那么cor1 和 cor2 就是兩個點了。
接著計算出距離distance就行了。
完整代碼:
import numpy as npfrom matplotlib.animation import FuncAnimationimport matplotlib.pyplot as pltfrom PIL import Imagedef on_press(event): global ix,iy global click_count global cor ix,iy = event.xdata, event.ydata coords = [] coords.append((ix,iy)) print("now = ", coords) cor.append(coords) click_count += 1 if click_count > 1: click_count = 0 cor1 = cor.pop() cor2 = cor.pop() distance = (cor1[0][0] - cor2[0][0]) **2 + (cor1[0][1] - cor2[0][1]) **2 distance = distance ** 0.5 print("distance = ", distance)cor = [0,0]click_count = 0fig = plt.figure()img = Image.open('0.jpg')#updata = Trueplt.imshow(img, animated= True)fig.canvas.mpl_connect('button_press_event', on_press)plt.show()
新聞熱點
疑難解答
圖片精選