简体   繁体   English

Tkinter.bind() 不调用子程序

[英]Tkinter .bind() not calling subprogram

I am trying to make a keylogger using Tkinter, but the binds are not working at all.我正在尝试使用 Tkinter 制作键盘记录器,但绑定根本不起作用。 I think the bind isn't calling the subprogram, but it provides no error so that is just an educated guess.我认为绑定没有调用子程序,但它没有提供任何错误,所以这只是一个有根据的猜测。

I started this project 3 days ago and expected it to be done yesterday.我在 3 天前开始了这个项目,并预计它会在昨天完成。 But this issue kept on cropping up, I am using python 3.6.1.但是这个问题不断出现,我使用的是 python 3.6.1。

Here is what I have already tried这是我已经尝试过的

  • Using lambda使用 lambda
  • Putting "command =" before the function在 function 之前加上“command =”
  • Changing "def keypress():" to "def keypress(event)"将“def keypress():”更改为“def keypress(event)”
  • Making the bind in a frame在框架中进行绑定
  • Binding each individual button the keyboard将每个单独的按钮绑定到键盘

I have even copied someone's keylogger code and came across the same issue (yes it was python-3.x)我什至复制了某人的键盘记录器代码并遇到了同样的问题(是的,它是 python-3.x)

It is made even more frustrating by the number of answers on forums that don't work and the days of googling and looking at the documentation.论坛上不起作用的答案数量以及谷歌搜索和查看文档的日子更加令人沮丧。

import tkinter
from tkinter import *

window = Tk()
window.title("Test")
window.config(bg = "white")

frame = Frame(window, width = 1000, height = 1000)
frame.place(x = 0, y = 0)

def keypress(event):
    print("pressed", repr(event.char)) #changed repr to str and also tried deleting it 

frame.bind("<Key>", lambda: keypress(event)) #other variations of this line include frame.bind("<key>", keypress), frame.bind("<key>", keypress()), frame.bind("<key>", keypress(event))

The expected input is just预期的输入只是

>>> Pressed [the key that I pressed]

but the output that you actually get is...但是您实际得到的 output 是...

>>>

Nothing.没有什么。

Any and all help would be wonderful, thanks in advance!任何和所有的帮助都会很棒,在此先感谢!

You don't need lambda if you aren't passing any arguments.如果您没有通过任何 arguments,则不需要lambda

frame.bind("<Key>", keypress)

Also, keybindings only work if the widget has the keyboard focus.此外,键绑定仅在小部件具有键盘焦点时才有效。 By default a frame does not get the keyboard focus.默认情况下,框架不会获得键盘焦点。 If you want to bind to a frame, you must force it to have keyboard focus:如果要绑定到框架,则必须强制它具有键盘焦点:

frame.focus_set()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM