要实现桌面图标的移动,我的想法是用python模拟鼠标点击来移动,可是怎么获得桌面各个图标的坐标,以及他们所代表的实际意义呢(比如知道某个图标是微信图标),因为之后需要根据它的不同名称来移动到不同的位置。
先实现截图,然后再用ocr,最后再使用pyuserinput
软件实现:
软件通过实时检测剪切板的内容来实现实时翻译
用的是百度基础翻译api,当然可以注册有道云的翻译api(翻译效果不错),不过只提供50块钱的翻译量(也不少。。。),我们加上tk可视化库来完成软件的大体功能。
百度api注册网址:http://fanyi-api.baidu.com/api/trans/product/prodinfo
点击总览 下方有申请信息 里面有app id 和密钥
然后上代码:
import http.client
import hashlib
import urllib
import random
import json
from tkinter import *
import win32clipboard,time
import threading
#百度翻译api
def translate(fromLang,toLang,q):
appid = '**********' # 填写你的appid
secretKey = '**********' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = fromLang #原文语种
toLang = toLang #译文语种
salt = random.randint(32768, 65536)
q= q
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
return result['trans_result'][0]['dst']
except Exception as e:
print (e)
finally:
if httpClient:
httpClient.close()
获取和设置剪切板内容:
#获取剪切板输入
def clipboard_get():
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return data
#设置剪切板输入
def clipboard_set(data):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, data)
win32clipboard.CloseClipboard()
主程序:
#主函数
def newmain(fromlang,to):
'''
fromlang:翻译源
to:翻译目标
'''
while 1:
data=clipboard_get()
if flag !='out':
if data !='404':
if data !='':
target=translate(fromlang,to,data)
fromres.set(data)
result.set(target)
clipboard_set('404')
else:
#print('不可为空')
pass
else:
#print('暂无数据')
time.sleep(2)
else:
print('退出')
break
全部代码:
#百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系translate_api@baidu.com
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
from tkinter import *
import win32clipboard,time
import threading
#百度翻译api
def translate(fromLang,toLang,q):
appid = '******' # 填写你的appid
secretKey = '*****' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
fromLang = fromLang #原文语种
toLang = toLang #译文语种
salt = random.randint(32768, 65536)
q= q
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
return result['trans_result'][0]['dst']
except Exception as e:
print (e)
finally:
if httpClient:
httpClient.close()
#获取剪切板输入
def clipboard_get():
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return data
#设置剪切板输入
def clipboard_set(data):
"""设置剪贴板数据"""
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, data)
win32clipboard.CloseClipboard()
#主函数
def newmain(fromlang,to):
'''
fromlang:翻译源
to:翻译目标
'''
while 1:
data=clipboard_get()
if flag !='out':
if data !='404':
if data !='':
target=translate(fromlang,to,data)
fromres.set(data)
result.set(target)
clipboard_set('404')
else:
#print('不可为空')
pass
else:
#print('暂无数据')
time.sleep(2)
else:
print('退出')
break
#汉译英 可调整翻译语言 参见百度api文档
def thread_zhToEn():
t1=threading.Thread(target=newmain,args=('zh','en'))
t1.start()
#英翻汉
def thread_EhToZn():
t2=threading.Thread(target=newmain,args=('en','zh'))
t2.start()
if __name__ == '__main__':
'''
flag:由于threading没有提供杀死线程,所以设置一个标识来结束函数
为防止tk卡死需要引入线程来完成翻译功能
'''
flag='1'
app=Tk()
app.title('翻译程序 author:liubingzhe')
app.geometry('800x600')
fromres=StringVar()
result=StringVar()
button_run=Button(app,text='汉译英',command=thread_zhToEn,width=800).pack()
button_run=Button(app,text='英译汉',command=thread_EhToZn,width=800).pack()
Label=Label(app,text='请退出后切换翻译模式').pack()
w = Message(app,textvariable=fromres,aspect=200,font=('微软雅黑','11')).pack()
w1 = Message(app,textvariable=result,aspect=200,font=('微软雅黑','11')).pack()
app.mainloop()
flag='out'
通过Ctrl-C复制内容,软件每隔两秒获取一次剪切板内容,通过调用百度翻译api来实现动态翻译,点击上方汉译英或英译汉来开启功能。
每隔两秒是为了防止剪切板接口由于频繁读取报错,不会影响软件体验。
可以调整message的aspect参数来调整显示的样式
当然也可以设定为固定值width来更好的优化显示效果
没有怎么优化,基本就是这个样子了
w = Message(app,textvariable=fromres,width=700,font=('微软雅黑','11')).pack()
w1 = Message(app,textvariable=result,width=700,font=('微软雅黑','11')).pack()
将其用pyinstaller打包做成桌面软件就可以啦.
要使用Python获取桌面图标的坐标和识别它们的实际意义,需要使用操作系统相关的API或库来实现。目前没有直接在Python中获取桌面图标信息的内置功能,因此需要借助第三方库来实现,下面是一个可能的解决方案:
由于不同操作系统的桌面图标布局方式不同,因此需要使用不同的方法来获取图标的坐标。
Windows操作系统:可以使用WinAPI来获取桌面图标的坐标。具体步骤如下:
ctypes
库。ctypes.windll.shell32.SHGetDesktopFolder
函数获取桌面文件夹的PIDL(可识别的标识符列表)。ctypes.windll.shell32.SHGetDesktopFolder
函数获取桌面对象。EnumObjects
方法获取桌面上的所有对象,包括图标。GetDisplayNameOf
方法获取每个对象的文件路径,并使用GetUIObjectOf
方法获取对象的图标位置。import ctypes
import win32com.shell.shell as shell
def get_desktop_icons():
pidl = ctypes.c_void_p()
shell.SHGetDesktopFolder().ParseDisplayName(0, 0, 'Desktop', None, ctypes.byref(pidl), 0)
desktop = shell.SHGetDesktopFolder().BindToObject(pidl, None, shell.IID_IShellFolder)
icons = []
for i in range(desktop.GetItemCount()):
item = desktop.GetItemAt(i)
name = desktop.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING)
icon = desktop.GetUIObjectOf(None, 1, (item,), shell.IID_IExtractIconW)
icon_info = icon.GetIconLocation()
icons.append((name, icon_info))
return icons
macOS操作系统:可以使用AppleScript或Objective-C来获取桌面图标的坐标。具体步骤如下:
subprocess
库。subprocess.check_output
函数执行AppleScript或Objective-C命令,获取桌面图标的坐标。import subprocess
import re
def get_desktop_icons():
applescript = """
tell application "Finder"
set desktopItems to every item of (desktop as alias)
set desktopIcons to {}
repeat with i from 1 to count of desktopItems
set desktopIcon to item i of desktopItems
set desktopIconPosition to position of desktopIcon
set end of desktopIcons to {name of desktopIcon, desktopIconPosition}
end repeat
end tell
return desktopIcons
"""
output = subprocess.check_output(['/usr/bin/osascript', '-e', applescript]).decode('utf-8')
icons = re.findall(r'\{([^}]+)\}', output)
icons = [tuple(icon.split(', ')) for icon in icons]
return icons
要识别图标的实际意义,可以使用图像处理和机器学习的方法。具体步骤如下:
cv2
和numpy
库。cv2.imread
函数读取需要识别的图标。import cv2
import numpy as np
def recognize_icon(image):
# 预处理图片,如去除背景、调整大小等
preprocessed_image = preprocess_image(image)
# 使用机器学习模型进行分类或目标检测,得到实际意义
return meaning
# 使用示例代码
image = cv2.imread('icon.jpg')
meaning = recognize_icon(image)
print(meaning)
以上是一个大致的解决方案,具体实现可能需要根据具体情况进行调整和优化。另外,由于涉及到操作系统和图像处理相关的内容,在不同的操作系统环境和Python版本下,可能会有所不同,需要根据具体情况选择合适的库和方法。