数字猜谜游戏的简单GUI

时间:2014-11-16 21:54:11

标签: user-interface random tkinter python-3.4

好吧,所以我删除了while循环并添加了Text字段,这样answer_txt将有一个回家。

现在它会起作用,但它总是说"太低"并且它不会允许多个条目。

我错过了什么?我相信这很接近。

from tkinter import *
import random
class Application(Frame):
    """ GUI Application for Number Guessing Game. """
    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
    # create widgets
    def create_widgets(self):
        Label(self,
              text = "Pick a number, 1 - 100: "
              ).grid(row = 0, column = 0, sticky = W)
        self.number_ent = Entry(self)
        self.number_ent.grid(row = 1, column = 1, sticky = W)
        Button(self,
               text = "Submit",
               command = self.get_answer
               ).grid(row = 2, column = 1, sticky = W)
        self.answer_txt = Text(self, width = 40, height = 10, wrap = WORD)
        self.answer_txt.grid(row = 3, column = 0, columnspan = 4)
    # get answer
    def get_answer(self):
        secret_num = random.randint(1, 100)
        number_ent = 0
        if number_ent < secret_num:
            answer = "Too low, guess again."
        elif number_ent > secret_num:
            answer = "Too high, guess again."
        elif number_ent == secret_num:
            answer = "Congratulations, you guessed right!"
        self.answer_txt.delete(0.0, END)
        self.answer_txt.insert(0.0, answer)
root = Tk()
root.title("Number Guess")
app = Application(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

你的GUI代码中不能有这样的while循环。 GUI仅在允许运行主循环时有效,并且只要您有自己的内部循环,mainloop就无法运行。

GUI编程与传统的自上而下的程序代码不同。使用GUI编程,您必须设置对事件做出反应的函数和变量。然后用户按下提交,你需要检查一两件事,然后返回。根据经验,任何响应按钮点击或事件而调用的函数运行时间不应超过几百毫秒。