Search code examples
pythontkinterpynput

pynput not letting tkinter make window


I have pynput reading keypresses if the Esc key has been pressed, and tkinter showing them in a window. Both work fine, but the moment I put them into one code, nothing happens. Here is my code:

import tkinter as tk
from pynput import keyboard

listen = False

def onpress(key):
    global listen
    if str(key) == 'Key.esc':
        listen = not listen
    if listen:
        if str(key) == 'Key.1':
            labelval.set(labelval.get()+'1')
            print('1')

win = tk.Tk()
labelval = tk.StringVar()
lab = tk.Label(win, textvariable=entryval)
lab.grid(column=0,row=0)

with keyboard.Listener(
    on_press = onpress) as listener:
    listener.join()

Nothing happens when I run it, the tk window doesn't show up, and the 1 doesn't get printed to the screen. Any suggestions? When I take out the listener.join(), everything works fine, but then it can't keylog


Solution

  • You have to run code between with and join() - and use mainloop() to show tkinter window

    with keyboard.Listener(on_press=onpress) as listener:
    
        win = tk.Tk()
        labelval = tk.StringVar()
        lab = tk.Label(win, textvariable=labelval)
        lab.grid(column=0,row=0)
        win.mainloop()
    
        listener.join()
    

    or at least mainloop()

    win = tk.Tk()
    labelval = tk.StringVar()
    lab = tk.Label(win, textvariable=labelval)
    lab.grid(column=0,row=0)
    
    with keyboard.Listener(on_press=onpress) as listener:
    
        win.mainloop()
    
        listener.join()
    

    You can write it also without with()

    listener = keyboard.Listener(on_press=onpress)
    listener.start()
    
    win = tk.Tk()
    labelval = tk.StringVar()
    lab = tk.Label(win, textvariable=labelval)
    lab.grid(column=0,row=0)
    win.mainloop()
    
    listener.join()
    

    BTW: you created labelval but you used textvariable=entryval

    On Linux I had to use different method to recognize 1

    import tkinter as tk
    from pynput import keyboard
    
    listen = False
    
    def onpress(key):
        global listen
    
        #if key == keyboard.Key.esc:
        if str(key) == 'Key.esc':
            listen = not listen
    
        if listen:
            if hasattr(key, 'char') and key.char == '1':
                labelval.set(labelval.get()+'1')
                print('1!')
    
    win = tk.Tk()
    labelval = tk.StringVar()
    lab = tk.Label(win, textvariable=labelval)
    lab.grid(column=0,row=0)
    
    with keyboard.Listener(on_press=onpress) as listener:
    
        win.mainloop()
    
        listener.join()