how can i detect if spacebar is pressed in tkinter without using other modules

Question:

from tkinter import *
root=Tk()
root.geometry("200x200")


def func(event):
    if event.char=="a":
        print("a is pressed")

root.bind("<KeyPress>",func)
root.mainloop()

here when a key is presssed it checks if it is "a" or not and prints "a is pressed"
just like that is there anyway to know if the key pressed is "space" or not with tkinter only

Asked By: suyog

||

Answers:

you have to bind to another function. use this code:

from tkinter import *
root=Tk()
root.geometry("200x200")


def func(event):
    if event.char=="a":
        print("a is pressed")
def func2():
    print("space is pressed")

root.bind("<KeyPress>",func)
root.bind("<space>",func2)
root.mainloop()
Answered By: eag-ehsan

The character for space is . The following should work.

def func(event):
    if event.char == ' ':
        print("Space is pressed")
Answered By: BlackBeans

Easier way to do this.

from tkinter import *
root=Tk()
root.geometry("200x200")


def func(event):
    if event.char=="a":
        print("a is pressed")
    elif event.char==" ":
        print("Space is pressed")
        

root.bind("<KeyPress>",func)
root.mainloop()
Answered By: toyota Supra
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.