Python - Opening a dialog box on key press

Viewed 12

I want to open a dialog box (that captures an input string from the user) when the user clicks a keyboard button. I'm using "tkinter" for the dialog box, and "pynput" for capturing keystrokes.

The dialog box works ok, if I'm placing the "simpledialog" command on the main code section. I fail to find a way to make it work only when I'm clicking a button (F2 in the following example):

import time  # For the delay function
from pynput import keyboard  # For catching keyboard strokes

import tkinter
from tkinter import simpledialog


# Execute functions based on the clicked key
def on_press(key):

    if key == keyboard.Key.f2:
        USER_INP = simpledialog.askstring(title="Test", prompt="What's your Name?:")

ROOT = tkinter.Tk()
ROOT.withdraw() # Hides tkinter's default canvas

# Assigning event to function
listener = keyboard.Listener(on_press=on_press)

# initiating listener
listener.start()

while 1 < 2:
    time.sleep(.01)

Can anyone help?

Thanks

1 Answers

Ok, in the meantime, I've solved it by doing two things:

  1. Moving the "simpledialog" back to the main code section (inside a while loop)
  2. Using a global variable to indicate whether I should open the dialog box.
import time  # For the delay function
from pynput import keyboard  # For catching keyboard strokes

import tkinter
from tkinter import simpledialog

openBox = False

# Execute functions based on the clicked key
def on_press(key):

    global openBox

    if key == keyboard.Key.f2:
        openBox = True


ROOT = tkinter.Tk()
ROOT.withdraw() # Hides tkinter's default canvas

# Assigning event to function
listener = keyboard.Listener(on_press=on_press)

# initiating listener
listener.start()

while 1 < 2:
    if openBox:
        USER_INP = simpledialog.askstring(title="Test", prompt="What's your Name?:")
        print(USER_INP)
        openBox = False

    time.sleep(.01)
Related