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
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()
The character for space is
. The following should work.
def func(event):
if event.char == ' ':
print("Space is pressed")
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()
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
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()
The character for space is
. The following should work.
def func(event):
if event.char == ' ':
print("Space is pressed")
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()