4

Trying to get used to the tkinter gui but I'm running into a problem with setting up an input box. I wanted to make a simple number guessing program using Entry to input an integer and a button to submit the guess. I'm getting an str to int conversion error when I use int(GuessBox.get()) and I'm not sure what to do.

ValueError: invalid literal for int() with base 10: ''

from tkinter import *
import random

def makeAGuess():
    guess = int(GuessBox.get())
    print(guess)

    if guess == Answer:
        print("you got it!")
        return False
    elif guess > Answer:
        print("Too High, try again")
        return True
    else :
        print("Too low, try again")
        return True

Answer = random.randint(1, 100)


main = Tk()
label = Label(main, text = "Guess a number")
label.pack()
GuessBox = Entry(master = main)
GuessBox.pack()
submitGuess = Button(master = main, text = "Submit Guess", command = makeAGuess())
submitGuess.pack()
main.mainloop()
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sox Keep You Warm
  • 691
  • 1
  • 9
  • 14
  • You say you get an exception, but you haven't posted it. Please give the full error, including the traceback. Your code also doesn't match what you say - you never call `int()`. – Gareth Latty May 29 '13 at 21:01
  • what is returned from `GuessBox.get()` when you get this error, is it all digits? – cmd May 29 '13 at 21:06
  • Alright, updated my post – Sox Keep You Warm May 29 '13 at 21:08
  • @user2426318 Your question happened to get answered here, but in future, please attach the **full** error with **full traceback** - it makes tracking down the bug much, much simpler. – Gareth Latty May 29 '13 at 21:43

1 Answers1

4

You need to pass the function as an object, don't call it.

submitGuess = Button( master = main, text = "Submit Guess", command = makeAGuess )

Otherwise makeAGuess is called when the Button is created, but not passed any arguments. With this change your code works perfectly for me.

Blutack
  • 355
  • 1
  • 3
  • 1
    AHHH, now it works, awesome! Thanks, thats been annoying me for the past hour! – Sox Keep You Warm May 29 '13 at 21:17
  • 1
    No problem. Coming from Java, the functions are objects thing is a big change. This stuff would be hidden in the reflection packages. Does mean you can do cool stuff like pass a function into another function, or store a list of functions... – Blutack May 29 '13 at 21:19