tkinter程序源碼:初識Python,如有不足請多指教。
import tkinter as tk
import keyboard # 安裝: pip install keyboard
from PIL import ImageGrab # pip install pillow
import time
from aip import AipOcr # pip install baidu-api或者下載sdk後解壓執行:執行python setup.py install
def center(win):
"""窗口居中函數"""
win.update_idletasks()
width = win.winfo_width() + 400
height = win.winfo_height() + 260
x = (win.winfo_screenwidth() // 2) - (width // 2)
y = (win.winfo_screenheight() // 2) - (height // 2)
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
window = tk.Tk()
window.title('截圖文字識別工具')
# window.geometry('600x400')
center(window)
def insert_point():
APP_ID = '你的app_id'
API_KEY = '你的api_key'
SECRET_KEY = '你的secret_key'
# 調用百度ocr的API,申請方式請自行百度。
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# 截取圖片(截圖軟件)
keyboard.wait(hotkey='alt+a')
keyboard.wait(hotkey='enter')
# 防止圖片還未緩存就調用
time.sleep(0.1)
# 保存圖片到電腦
image = ImageGrab.grabclipboard()
image.save('WzTp.jpg')
""" 讀取圖片 """
with open('WzTp.jpg', 'rb') as file:
image = file.read()
text = client.basicAccurate(image)
res = text['words_result']
for i in res:
print(i['words'])
# var = e.get()
t.insert('insert', i['words']+'\n')
t.insert('insert', '\n-----------------------------------------------------------------\n')
b1 = tk.Button(window, text='啓動程序', width=20, height=2, command=insert_point) #光標處插入
b1.pack()
t = tk.Text(window, height=25)
t.pack()
l = tk.Label(window, text='使用方法:Alt+A截圖,然後Enter結束', width=30, height=1)
l.pack(expand='yes', fill='x')
window.mainloop()
軟件截圖如下: