Working on a number guessing assignment for an informatics course and cannot for the life of me on this program bind this key. Using previous programs and class example I am able to bind this key to perform certain functions however not in this particular one. Therefore, I am assuming there is something super small wrong and im just overlooking it. Any help is appreciated.
from tkinter import *
import random
class Application(Frame):
def __init__(self, master): #sets up gui elements
Frame.__init__(self, master)
self.grid()
self.create_widgets()
self.number = random.randint(0, 9)
def create_widgets(self):
# creates instructions
Label(self, text = "I'm thinking of a number between 0 and 9.").grid(row = 0, column = 0, sticky = W)
Label(self, text = "Try and guess it!").grid(row = 1, column = 0, sticky = W)
# create guess label and entry
Label(self, text = "Your guess:").grid(row = 2, column = 0, sticky = W)
self.guess_ent = Entry(self)
self.guess_ent.grid(row = 2, column = 1, sticky = W)
# creates button to initiate run function
self.bttn=Button(self, text = "Submit", command = self.run)
self.bttn.grid(row = 3, column = 1, sticky = W)
#binds return key
self.bttn.bind('<KeyPress>', self.enter)
self.bttn.focus_set()
# creates feedback text box for run function
self.text = Text(self, width = 75, height = 10, wrap = WORD)
self.text.grid(row = 4, column = 0, columnspan = 4)
def run(self):
#gets random number
guess = int(self.guess_ent.get())
#if to test guesses and give appropriate feedback
if guess != self.number:
print_text = "You guessed {0}.".format(guess)
if guess > self.number:
print_text += " That's too high. Guess lower..."
elif guess < self.number:
print_text += " That's too low. Guess higher..."
self.text.delete(0.0, END)
self.text.insert(0.0, print_text)
self.guess_ent.delete(0, END)
else:
print_text = "That's the right number! You did it!!"
self.text.delete(0.0, END)
self.text.insert(0.0, print_text)
def enter(self, event):
if event.keysym == "Return":
self.run()
# main
root = Tk()
root.title("Number Guesser")
app = Application(root)
root.mainloop()
The return key in tkinter is also Return
, hence your code should be :
self.bttn.bind('<Return>', self.enter)
You are binding the key to a button which does not get focus until pressed or tabbed into, making it almost impossible to notice the trigger of the binding, because your button and the bind call the same method.
Bind to the Entry
widget such that you can trigger the binding while in the widget:
self.guess_ent.bind('<Return>', self.enter)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.