一些工作环境非常讲究数据安全,导致有些兄弟部署的电脑上面不能连网、也不能插U盘。所以无法导入第三方库,此为本文的用武之地。
注意:
1.本文代码使用tab缩进,非四个空格缩进,直接复制粘贴的朋友要注意和你要整合的代码是不是一样的缩进方式。
2.仅在python3.8,windows10,window7平台测试过,linux与mac估计是不能用的,windows上的python2肯定也是不能用的,python3.4以下估计也有点悬。
3.鼠标位置更新的间隔时间是0.1秒,要更快需要自行改代码中的设置。
贴上代码:
import ctypes
import ctypes.wintypes
from tkinter import *
from time import sleep
import threading
import platform # 电脑系统以及python版本检测
# 为了保证通用性,需要降低对第三方库的依赖,尽可能使用内置库
def get_mouse_cursor_position():
"""Returns 当前 鼠标光标 的x,y坐标 (x:int, y:int)
通过调用 GetCursorPos()这个 win32 方法.
"""
cursor = ctypes.wintypes.POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))
return (cursor.x, cursor.y)
def get_screen_size(): # 获取屏幕分辨率,用于计算软件图形界面显示位置
return (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
def get_mouse_position_thread(): # 定义了线程的循环动作
global show_label
while True:
try:
mouse_x,mouse_y = get_mouse_cursor_position()
if show_label: # 这个判定是因为有可能图形界面被不小心关掉了(如果整合其他功能就有可能用上)
show_label.config(text = str(mouse_x) + ',' + str(mouse_y))
except Exception as e:
print('更新鼠标位置时发生错误:',e)
if input('如果想要线程继续运行,请输入1\n') == '1': # 发生错误后输入数字1并回车,线程忽视错误,继续下一个循环
print('线程继续尝试运行')
continue
else:
print('中止线程运行')
break
sleep(0.1) # 间隔时间
def main():
global show_label
_win_ver_num = platform.platform().split('-')
if _win_ver_num[0] != 'Windows': # 检测运行系统
print(f'程序设计运行于windows平台上,本机{_win_ver_num[0]}系统无法运行(3秒后自行结束)!')
sleep(3)
else:
_py_ver_num = platform.python_version().split('.') # 检测是不是python3
if int(_py_ver_num[0]) != 3:
print(f'程序仅运行在python3平台上,本机为python{_py_ver_num[0]},无法运行(3秒后自行结束)!')
sleep(3)
else:
if int(_py_ver_num[1]) < 8: # 检测python版本,python 3.6说不定也可以
print('程序仅在python3.8上测试过运行!,本机上可能会出现异常!')
# 更改控制台窗口标题,不再是什么py.exe,这样就能和同时运行的其他python程序区分了
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p('鼠标位置显示器控制台'))
show_label = None
t1 = threading.Thread(target = get_mouse_position_thread)
t1.setDaemon(True)
t1.start()
screen_x,screen_y = get_screen_size()
root = Tk()
root.geometry('+' + str(screen_x - 170) + '+' + str(screen_y - 240))
root.title('鼠标位置')
root.attributes('-toolwindow',1,'-topmost',1)
Label(root,text = '当前鼠标位置:',fg='Maroon').grid(row = 0 ,column =0)
show_label = Label(root,text = '无,无',fg='Green')
show_label.grid(row = 0 ,column =1)
root.mainloop()
if __name__ == '__main__':
main()