python tkinter+ autohotkey更改键盘键位映射

autohotkey键位查阅
AHK按键参考表(仅用于查阅)
中文手册

tkinter官网
较好的中文教案

我其中的一个ahk文件:

Delete::AppsKey
Insert:: Ctrl
b::[
a::t
n::r
h::j
x::w
o::e
j::p
d::o
m::n
;偏心

使用Ahk2exe将ahk 文件编译成exe文件,可在autohotkey官网下载

代码如下

import os, time, threading
import psutil, tkinter, subprocess
import tkinter.messagebox
from tkinter import ttk

from typing import Optional
from ctypes import  windll, create_unicode_buffer


def getForegroundWindowTitle() -> Optional[str]:
    hWnd = windll.user32.GetForegroundWindow()
    length = windll.user32.GetWindowTextLengthW(hWnd)
    buf = create_unicode_buffer(length + 1)
    windll.user32.GetWindowTextW(hWnd, buf, length + 1)
    return buf.value if buf.value else None


class Keylisten:
    def __init__(self):
        with open('./radardict.txt', 'r',encoding='utf-8') as fp:
            content = eval(fp.read())
        self.radar_type = content
        self.radars = [r for r in self.radar_type.keys()]
        self.ahks = [r for r in self.radar_type.values()]
        self.chosed = None  # 选中的xx

        pass

    def radar_choosed(self, event):
        widget = event.widget  # 当前的组件
        value = widget.get()
        self.chosed = value

    # 获取窗口
    def wingui(self):
        flag = False
        title = getForegroundWindowTitle()
        if '模拟xxx方位距离录取席' == title:
            flag = True
        return flag

    # 启动ahk
    def start_ahk(self):
        self.pid = os.getpid()
        self.kill_all_process()
        if self.chosed in self.radars:
            self.radarkey = self.radar_type.get(self.chosed)
            while 1:
                flag = self.wingui()
                if flag:
                    time.sleep(1)
                    os.popen("start {}".format(os.getcwd() + '\\chk\\' + self.radarkey))
                    break
                time.sleep(1)
                print("over!")
        else:
            pass

    def start_Main(self):
        subprocess.Popen('.//MainManipulator.exe', shell=False)

    # 杀掉所有与ahk有关的进程
    def kill_all_process(self):
        pids = psutil.process_iter()
        for pid in pids:
            try:
                if pid.name() in self.ahks:
                    process = psutil.Process(pid.pid)
                    process.kill()
            except Exception as e:
                print(e)

    # 杀掉当前的ahk进程
    def kill_current_proccess(self):

        try:

            pids = psutil.process_iter()
            radarexe = self.radar_type.get(self.chosed)
            for pid in pids:
                try:

                    if pid.name() == radarexe:
                        process = psutil.Process(pid.pid)
                        process.kill()
                        break
                except Exception as e:
                    print(e)
            process = psutil.Process(self.pid)
            process.kill()
            print(radarexe)
        except Exception as e:
            print(e)

        self.root.destroy()

    # tkinter窗口设置
    def tkinter_window(self):
        def xd_db():
            subprocess.Popen('./专业训练通用想定制作.exe', shell=False)

        def click_db():
            if self.chosed:
                threadfunc1 = threading.Thread(target=self.start_ahk, args=[])
                threadfunc1.start()
                subprocess.Popen('.//MainManipulator.exe', shell=False)
                # threadfunc2 = threading.Thread(target= self.start_Main, args=[])
                # threadfunc2.start()
            else:
                tkinter.messagebox.showerror(title='错误通告', message='请选择型号!')

        self.root = tkinter.Tk()
        self.root.protocol('WM_DELETE_WINDOW', self.kill_current_proccess)  # 关掉窗口的同时杀掉ahk有关进程
        self.root.title("练习9  v2.0")
        screenwidth = self.root.winfo_screenwidth()  # 屏幕宽度
        screenheight = self.root.winfo_screenheight()  # 屏幕高度
        x = int((screenwidth - 360) / 2)
        y = int((screenheight - 290) / 2)
        self.root.geometry("360x240+{0}+{1}".format(x, y))
        self.root.iconbitmap(".//icon.ico")
        # 背景
        C = tkinter.Canvas(self.root, bg="blue", height=290, width=360)
        filename = tkinter.PhotoImage(file="bg.gif", height=290, width=360)
        background_label = tkinter.Label(self.root, image=filename)
        background_label.place(x=0, y=0, relwidth=1, relheight=1)
        C.pack()
        font = ("HeiTi", 18, 'bold')
        # 下拉框设置
        value = tkinter.StringVar()
        value.set('请选择型号')
        combobox = ttk.Combobox(
            master=self.root,  # 父容器
            height=20,  # 高度,下拉显示的条目数量
            width=20,  # 宽度
            state='readonly',  # 设置状态 normal(可选可输入)、readonly(只可选)、 disabled
            cursor='arrow',  # 鼠标移动时样式 arrow, circle, cross, plus...
            font=('', 16),  # 字体
            justify="center",  # 对齐方式
            textvariable=value,  # 通过StringVar设置可改变的值
            values=self.radars,  # 设置下拉框的选项
        )
        combobox.bind('<<ComboboxSelected>>', self.radar_choosed)
        combobox.place(x=62, y=115, anchor='w')
        # buttun设置

        btn_xd = tkinter.Button(self.root, text='想定制作', command=xd_db, font=font, width=18, height=1, bg='#fc5531',
                             fg='#fff', borderwidth=0, )
        btn_xd.place(x=60, y=60, anchor='w')

        btn_xl = tkinter.Button(self.root, text='开始训练', command=click_db, font=font, width=18, height=1, bg='#e4f4fb',
                             fg='#037dfb', borderwidth=0, )
        btn_xl.place(x=60, y=170, anchor='w')
        self.root.mainloop()


k = Keylisten()
k.tkinter_window()
# pyinstaller -F -w -i .\logo.ico xz32.py

最后用pyinstaller打包

pyinstaller -F -w -i .\logo.ico xz.py
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值