Mostafa
Mostafa

Reputation: 63

event keyboard does not work in tkinter

I do not know why the event does not work with my script. It seems logical but I do not know why it does not go to the specified function. here is my script

from tkinter import *


root = Tk()

start = Label(root, text="press 's' to start the game.")
start.pack()
quitGame = Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def start(event):
    if event.char == 's':
        print("Start")

def exit(event):
    if event.char == 'q':
        root.quit


frame = Frame(root, width=800, height=600)
root.bind('<Key>', start)
root.bind('<Key>', exit)
frame.pack()

root.mainloop()

Upvotes: 0

Views: 162

Answers (1)

Novel
Novel

Reputation: 13729

When you call bind, you also unbind all other function from that event. There is a way to bind multiple functions but in your case it would be better to combine your functions into one.

import tkinter as tk

root = tk.Tk()

start = tk.Label(root, text="press 's' to start the game.")
start.pack()
quitGame = tk.Label(root, text="press 'q' to quit the game.")
quitGame.pack()

def key_pressed(event):
    if event.char == 's':
        print("Start")
    if event.char == 'q':
        root.quit()

frame = tk.Frame(root, width=800, height=600)
root.bind('<Key>', key_pressed)
frame.pack()

root.mainloop()

Also, try to avoid using wildcard imports; they only lead to confusing code and bugs.

Upvotes: 2

Related Questions