Python示例代码之钩子

     

     钩子通常称为回调函数,在应用中常见于系统的键盘鼠标获取,或界面中按钮、复选框等按键的处理函数,如下分别描述。   

      键盘鼠标获取

      鼠标键盘需要使用pythoncom和pyHook的库,代码见下,其中onMouseEvent和onKeyboardEvent是回调函数。

import pythoncom
import pyHook
import time

def onMouseEvent(event):
  fobj.writelines('-' * 22 + 'MouseEvent Begin' + '-' * 22 + '\n')
  fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  fobj.writelines("Message:%d\n" % event.Message)
  fobj.writelines("Time_sec:%d\n" % event.Time)
  fobj.writelines("Window:%s\n" % str(event.Window))
  fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  fobj.writelines("Position:%s\n" % str(event.Position))
  fobj.writelines('-' * 22 + 'MouseEvent End' + '-' * 22 + '\n')
  return True

def onKeyboardEvent(event):
  fobj.writelines('-' * 22 + 'Keyboard Begin' + '-' * 22 + '\n')
  fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  fobj.writelines("Message:%d\n" % event.Message)
  fobj.writelines("Time:%d\n" % event.Time)
  fobj.writelines("Window:%s\n" % str(event.Window))
  fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  fobj.writelines("Ascii_code: %d\n" % event.Ascii)
  fobj.writelines("Ascii_char:%s\n" % chr(event.Ascii))
  fobj.writelines("Key:%s\n" % str(event.Key))
  fobj.writelines('-' * 22 + 'Keyboard End' + '-' * 22 + '\n')
  return True

file_name = "hook_log.txt"
fobj = open(file_name, 'w')
hm = pyHook.HookManager()
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()
hm.MouseAll = onMouseEvent
hm.HookMouse()
pythoncom.PumpMessages()
fobj.close()

      执行完毕后打开“hook_log.txt”文件,查看有诸多键盘和鼠标的消息打印。

      界面中按钮事件

      界面中的按钮事件例子如下, 其中btn_click_action为回调函数。

from tkinter import *
import tkinter.messagebox

class ProjectGUI():
    
    def btn_click_action(self):
        tkinter.messagebox.showinfo('提示','人生苦短')
                
    def test_gui(self):
        tip_dlg = Tk(className = "Tips")
        tip_dlg.resizable(width = False, height = False)
        tip_button = Button(tip_dlg, bg = 'Green',fg = 'white', text="you can click me.", command = lambda:self.btn_click_action(tip_button), font = ("Times New Roman", 30)).pack(side='top')    
        tip_dlg.update() 
        tip_dlg.deiconify()
        scrnW = tip_dlg.winfo_screenwidth()
        scrnH = tip_dlg.winfo_screenheight()
        width = tip_dlg.winfo_width()
        height = tip_dlg.winfo_height()
        left = (scrnW - width) / 2
        top = (scrnH - height) / 2 - 50
        tip_dlg.geometry('+%d+%d' % (left, top))
        tip_dlg.deiconify()
        tip_dlg.mainloop()

gui = ProjectGUI()
gui.test_gui()

      代码运行之后,界面如下所示:

如果您喜欢这篇文章,别忘了点赞和评论!

发布了172 篇原创文章 · 获赞 93 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/chenzhanhai/article/details/86254332