Rable
Rable

Reputation: 65

use tkinter to keybind functions without having focus

i cant find a way to start the run function by pressing a key while not giving focus to the tkinter window, i also need to be able to stop the function while its runing by pressing the key again

import time
import keyboard
from tkinter import *
import re

def run(debug=None,):
    while True:
        if keyboard.is_pressed('q'):
            return()
        else:        
            print(debug)
            print("2")
            print("4")
            print("6")
            print("8")
            
    
    


window = Tk()

window.title("pain")

window.geometry('350x200')
#widgets
label = Label(window, text="fuck off")
label.grid(column=0, row=0)

button = Button(window, text="Click Me")
button = Button(window, text="Click Me", command=run)
button.bind('<Enter>',run)
button.grid(column=1, row=0)
#other stuff
window.bind('q',run)


window.mainloop()  

im new to coding so im unsure if this is even possible

Upvotes: 0

Views: 314

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

Tkinter can only respond to keyboard events if the tkinter app has keyboard focus. If you need the code to respond to events when it doesn't have focus you'll have to find some sort of platform-specific library.

Upvotes: 1

Related Questions