【问题标题】:Guess my number game and GUI = stumped :(猜猜我的数字游戏和 GUI = 难倒:(
【发布时间】:2015-11-10 19:41:35
【问题描述】:

我是一名初学者,在将“猜我的数字游戏”整合到 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()

【问题讨论】:

  • 一般来说,Tkinter 应用程序不应该有 while 循环来等待小部件改变状态,因为窗口不会重绘或响应用户输入,除非你经常通过让你的功能结束。这里没有真正的“快速修复”;您需要使用有状态/响应式范例来设计程序,而不是控制台程序的“落石”风格。
  • 好的。谢谢,很高兴知道。我会放弃 while 循环,看看我能想出什么。

标签: python tkinter


【解决方案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()

【讨论】:

  • 哈哈!有一次,我确实在构造函数中使用了 self.number,但 while 循环仍然存在。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多