4

试图习惯 tkinter gui,但我在设置输入框时遇到了问题。我想制作一个简单的数字猜测程序,使用 Entry 输入一个整数和一个按钮来提交猜测。当我使用 int(GuessBox.get()) 时出现 str 到 int 的转换错误,我不知道该怎么做。

ValueError: int() 以 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()
4

1 回答 1

4

您需要将函数作为对象传递,不要调用它。

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

否则,在创建 Button 时调用 makeAGuess,但不传递任何参数。通过此更改,您的代码非常适合我。

于 2013-05-29T21:14:51.613 回答