不使用变量

时间:2018-11-24 20:37:21

标签: python tkinter

这是我在这里的第一个问题,所以如果我做错了,请不要生气。我得到了猜测密码的家庭作业,因此不得不在其中实施Tkinter。问题在于,由于未使用变量计数器,因此计数器无法正常工作。我知道了,但是我很难按原样编写它,看起来好像没有。对于另一个问题,下面我再次使用IF的其他语句,这样可以吗?还是您练习其他代码?

    import Tkinter
    import random
    import tkMessageBox

    secret_number = random.randint(1, 10)

    window = Tkinter.Tk()

    greeting = Tkinter.Label(window, text="Welcome to the game " + "guess the secret number".upper() + ". You have 5 tries.\n Select a number between 1 and 10:")
    greeting.pack()


    guess = Tkinter.Entry(window)
    guess.pack()


    def check_guess():
        counter = 0
        if int(guess.get()) == secret_number:
            counter = counter + 1 #here it states "variable not used"
            result_text = "You guessed correctly! Secret number is %s! " % secret_number
        elif int(guess.get()) > secret_number:
            counter = counter + 1
            result_text = "Wrong. Your number is to HIGH! This was your %s try." % counter
        else:
            counter = counter + 1
            result_text = "Wrong. Your number is to LOW! This was your %s try." % counter
        if counter == 5 and guess != secret_number:
            print "Secret number was %s!" % secret_number

        tkMessageBox.showinfo("Result", result_text)


    submit = Tkinter.Button(window, text="Try your luck", command=check_guess)  # check_guess, not check_guess()
    submit.pack()

    window.mainloop()

1 个答案:

答案 0 :(得分:1)

每次调用该函数时,<Cannot do="update" on="style"> <button disabled={true}> Update </button> </Cannot> 都将设置为0,这意味着它将永远不等于5。一个简单的解决方法是改用全局变量。而是在函数外设置counter,然后从函数中删除该行。而是在函数的第一行写counter = 0。像这样:

global counter