python 组合键_如何在Python中实现组合键(包括修饰键)?

在Python中实现组合键,特别是当使用turtle库时,可以借助pykeyboard库来实现。通过创建键盘对象并调用其press_key、tap_key和release_key方法,能够模拟按下、释放键的操作,从而实现如CTRL+P这样的组合键操作。此外,还可以使用type_string方法输入自定义字符串,自动化文件保存等任务。

I am wondering about bow to implement two-key combinations in Python. I am utilizing the turtle.onkey() function since I am using turtle graphics, but it seems like it is not very versatile, as I cannot find a way for it to take key combinations. So, is there any other way to implement key combinations in python? Any help regarding this issue is very much appreciated! :)

解决方案

I use pykeyboard ( with Python 2.7 ) to "simultaneously press" 2 keyboard keys as a hotkey. The pykeyboard package comes installed with the PyUserInput installation.

Code Example : If I want to automatically have my program hit the hotkey combination ( CTRL + P ) to print something without me laying a finger on the keyboard, here is how I would do it through pykeyboard.

import pykeyboard

keyboard_object = pykeyboard.PyKeyboard()

I begin by creating my keyboard object as shown above.

keyboard_object.press_key ( keyboard_object.control_key )

keyboard_object.tap_key ( "P" ) # Upper-Case

keyboard_object.release_key ( keyboard_object.control_key )

That should bring up the print window and I could have it continue forward to print on the default setting by having my script hit the Enter Key.

keyboard_object.tap_key ( keyboard_object.enter_key )

I can even have my script type custom strings. This can be useful if I want to save a file by a specified string in an automated form. I'll begin with the ( CTRL + S ) hotkey combination.

keyboard_object.press_key ( keyboard_object.control_key )

keyboard_object.tap_key ( "S" ) # Upper-Case

keyboard_object.release_key ( keyboard_object.control_key )

The "Save-As" window should pop up, prompting me to specify the filename that I want to have saved. So I'll pass that as a string.

keyboard_object.type_string ( "MyFilename-03_22_2016.html" )

keyboard_object.tap_key ( keyboard_object.enter_key )

Voila!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值