问题描述
我在想是否有任何方法可以绑定GLOBAL"tk/ttk 小部件的键绑定
I am thinking if there is any way to bind "GLOBAL" key bindings to tk/ttk widgets
例如:在这段代码中:
import tkinter as tk
def output(lines = 'hehehehe'):
print(lines)
root = tk.Tk()
button = tk.Button(root, text ='HAHAHA', command = lambda:output('hahaha'))
button.pack()
root.bind('<Control-a>', output)
root.mainloop()
现在,每当我在窗口处于活动状态时按下 Control+A,函数 output()
就会起作用..
now, whenever i hit Control+A when the window is active, the function output()
works..
但是,当我启动任何其他窗口并使该 tk-window 处于非活动状态时,键绑定不起作用...
But, when i start any other window and make this tk-window inactive, The key bindings doesn't work...
有没有办法绑定全局"?
Is there any way to bind "GLOBALLY"?
推荐答案
不可能,你不能在 tkinter
中访问全局击键,你必须使用一些其他的外部库,比如 键盘
,应该相当简单.
Not possible, you cannot access global key-strokes within tkinter
, you will have to use some other external library like keyboard
, should be fairly easy.
首先使用 pip install keyboard
安装库,然后:
First install the library with pip install keyboard
, then:
import tkinter as tk
import keyboard
....
keyboard.add_hotkey('ctrl+a', output, args=('From global keystroke',))
root.mainloop()
这篇关于python tkinter - 绑定一个“全局"可从窗口外触发的快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!