【发布时间】: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 循环,看看我能想出什么。