猜猜我的数字游戏和GUI =难倒:(

时间:2015-11-10 19:41:35

标签: python tkinter

我是初学者,我在将一个'猜我的号码游戏'纳入GUI时遇到了一个真正的问题。这是“绝对初学者的Python编程”的挑战,书中没有解决方案吗?!

我可以得到一个猜测并通过一个while循环运行它,但此后我不知所措。我花了好几个小时尝试各种各样的东西,并且没有任何可行的东西。我可能偏离轨道。

我希望能够从用户那里得到进一步的猜测,但是如何在GUI中?

谢谢, 戴夫(累了,士气低落)

My code:

# Guess my number game
# User must attempt to guess randomly selected number within a range in fewest possible attempts

from Tkinter import *
import random

class Application(Frame):
    """A GUI application which which generates random number and gets user input"""

    def __init__(self, master): #initialize newly created Application object
        """Initialize the frame"""
        Frame.__init__(self, master) # super(Application, self).__init__(master) in python 3
        self.grid()
        self.create_widgets()


    def create_widgets(self):
        """Get user inputs"""
        # create instruction label
        Label(self, text = "I'm thinking of a number between 1 and 100.").grid(row = 0, column = 0, sticky = W)
        Label(self, text = "Try and guess it in as few attempts as possible!").grid(row = 1, column = 0, sticky = W)

        # create guess input prompt label and entry
        Label(self, text = "Take a guess:").grid(row = 2, column = 0, sticky = W)
        self.guess_ent = Entry(self)
        self.guess_ent.grid(row = 2, column = 1, sticky = W)

        # create start game prompt label and submit button
        Label(self, text = "Press submit to start the game!").grid(row = 3, column = 0, sticky = W)
        Button(self, text = "Submit", command = self.run_game).grid(row = 3, column = 1, sticky = W)


        # create submit button
        #Button(self, text = "Submit", command = )

        # create computer feedback text box
        self.text = Text(self, width = 75, height = 10, wrap = WORD)
        self.text.grid(row = 4, column = 0, columnspan = 4)





    def run_game(self):
        """Generate number and get user input"""
        guess = int(self.guess_ent.get())
        number = random.randint(1, 101)

        while guess and guess != number:
            print_text = ""
            print_text += "You guessed "
            print_text += str(guess)
            print_text += "."

            if guess > number:
                print_text += " That's too high. Guess lower..."
            elif guess < number:
                print_text += " That's too low. Guess higher..."

            self.text.delete(0.0, END)
            self.text.insert(0.0, print_text)

            self.guess_ent.delete(0, END)



        #print_text = ""    
        #print_text += "That's the right number! Well done!"
        #self.text.delete(0.0, END)
        #self.text.insert(0.0, print_text)


# main
root = Tk()
root.title("Guess my number game!")
app = Application(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

轻松解决此问题。将number = random.randint(1, 101)移至__init__函数并将其设为自变量。然后将while替换为if并完成。完整代码看起来像这样。我对print_text做了一些小改动,因为不需要4行代码来构造字符串。并将number更改为self.number

# Guess my number game
# User must attempt to guess randomly selected number within a range in fewest possible attempts

from tkinter import *
import random

class Application(Frame):
    """A GUI application which which generates random number and gets user input"""

    def __init__(self, master): #initialize newly created Application object
        """Initialize the frame"""
        Frame.__init__(self, master) # super(Application, self).__init__(master) in python 3
        self.grid()
        self.create_widgets()
        self.number = random.randint(1, 101)

    def create_widgets(self):
        """Get user inputs"""
        # create instruction label
        Label(self, text = "I'm thinking of a number between 1 and 100.").grid(row = 0, column = 0, sticky = W)
        Label(self, text = "Try and guess it in as few attempts as possible!").grid(row = 1, column = 0, sticky = W)

        # create guess input prompt label and entry
        Label(self, text = "Take a guess:").grid(row = 2, column = 0, sticky = W)
        self.guess_ent = Entry(self)
        self.guess_ent.grid(row = 2, column = 1, sticky = W)

        # create start game prompt label and submit button
        Label(self, text = "Press submit to start the game!").grid(row = 3, column = 0, sticky = W)
        Button(self, text = "Submit", command = self.run_game).grid(row = 3, column = 1, sticky = W)


        # create submit button
        #Button(self, text = "Submit", command = )

        # create computer feedback text box
        self.text = Text(self, width = 75, height = 10, wrap = WORD)
        self.text.grid(row = 4, column = 0, columnspan = 4)

    def run_game(self):
        """Generate number and get user input"""
        guess = int(self.guess_ent.get())

        if guess != self.number:
            print_text = "You guessed {0}.".format(guess)

            if guess > self.number:
                print_text += " That's too high. Guess lower..."
            elif guess < self.number:
                print_text += " That's too low. Guess higher..."

            self.text.delete(0.0, END)
            self.text.insert(0.0, print_text)

            self.guess_ent.delete(0, END)
        else:
            print_text = "That's the right number! Well done!"
            self.text.delete(0.0, END)
            self.text.insert(0.0, print_text)

# main
root = Tk()
root.title("Guess my number game!")
app = Application(root)
root.mainloop()