简体   繁体   中英

python tkinter entry command can't convert to int

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()

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM