[Python] Python - Tkinter registers keypress (when it is not, in fact, pressed)

Discussão em 'Python' iniciado por Stack, Agosto 24, 2025.

  1. Stack

    Stack Membro Participativo

    I'm making a simple word game. The game itself is pretty much done, and works with no bugs; I'm just trying to add some quality of life. The one I'm stuck on is making the Enter/Return key on the keyboard perform the same function as the Guess button. The Guess button works perfectly. But, unfortunately, my program just presses Enter and calls self.submit() as soon as the application starts. I don't want this. Here's my current code (simplified, a lot, to remove the bulk of the game which works).

    import tkinter as tk
    from tkinter import ttk

    class App(tk.Frame):
    def __init__(self, master):
    tk.Frame.__init__(self, master, height=900, width=900)
    self.entry = tk.Entry(self)
    self.entry.focus()
    self.entry.pack()
    self.clear_button = tk.Button(self, text="Guess", command=self.submit)
    self.clear_button.pack()
    self.bind("<Return>", self.submit()) #this is the line I just added. It's not working.

    def submit(self):
    print("pressed enter") #(to debug; it does print this)
    #here I have all the required code to guess a word

    def main():
    root = tk.Tk()
    App(root).pack(expand=True, fill='both')
    root.mainloop()

    if __name__ == "__main__":
    main()


    Is the issue something to do with keyboard focus? I'm still fairly new so haven't yet figured out how that works. Or is it a silly mistake I've missed? Would appreciate any help. Thanks a lot!

    Continue reading...

Compartilhe esta Página