简体   繁体   中英

Tkinter .bind() not calling subprogram

I am trying to make a keylogger using Tkinter, but the binds are not working at all. 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. But this issue kept on cropping up, I am using python 3.6.1.

Here is what I have already tried

  • Using lambda
  • Putting "command =" before the function
  • Changing "def keypress():" to "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)

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...

>>>

Nothing.

Any and all help would be wonderful, thanks in advance!

You don't need lambda if you aren't passing any arguments.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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