【发布时间】:2019-12-09 06:32:16
【问题描述】:
我正在猜测 Zelle 图形中的数字,但我的程序似乎无法正常运行。我试图让文本条目成为一个整数。如果我所做的工作有任何其他问题,我将不胜感激。
我尝试过 int(number) 但没有成功
from graphics import *
import random
hidden=random.randrange(1,10)
def responseDict():
levels = dict()
levels['high'] = 'woah! you are too high!'
levels['low']='oh no! that is too low'
levels['equal']='yes, this is just right!'
return levels
def circles(): # cute, but nothing original here, not even usage
win = GraphWin("Random Circles",300,300)
for i in range(300):
r = random.randrange(256)
b = random.randrange(256)
g = random.randrange(256)
color = color_rgb(r, g, b)
radius = random.randrange(3, 40)
x = random.randrange(5, 295)
y = random.randrange (5, 295)
circle = Circle(Point(x,y), radius)
circle.setFill(color)
circle.draw(win)
time.sleep(.05)
def textBox(win):
message = Text(Point(250,50),'Please guess a number 1 through 10 then click outside the box')
message.draw(win)
message2=Text(Point(250,100),'You have 4 tries, to guess the number correctly.')
message2.draw(win)
for i in range(9):
textEntry =Entry(Point(233,200),10)
textEntry.draw(win)
win.getMouse()
number=textEntry.getText()
guess=int(number)
print(guess)
levels = responseDict()
while guess != hidden:
if guess < hidden:
response = Text(Point(300,300), (levels['low']))
response.draw(win)
again=Text(Point(400,400), 'guess again')
again.draw(win)
textEntry=Entry(Point(233,200),10)
textEntry.draw(win)
win.getMouse()
number=textEntry.getText()
guess=int(number)
print(guess)
response.undraw()
again.undraw()
win.getMouse()
elif guess > hidden:
response2=Text(Point(350,350),(levels['high']))
response2.draw(win)
again2=Text(Point(400,400), 'guess again')
again2.draw(win)
textEntry2=Entry(Point(233,200),10)
textEntry2.draw(win)
win.getMouse()
number=textEntry.getText()
guess=int(number)
print(guess)
response2.undraw()
again2.undraw()
win.getMouse()
else:
response=Text(Point(300,300),(levels['equal']))
response.draw(win)
win.getMouse()
circles()
win = GraphWin('guess number', 700,700)
win.setBackground('brown')
textBox(win)
exitText = Text(Point(400,400), 'Click anywhere to quit')
exitText.draw(win)
win.getMouse()
win.close()
我希望用户输入的内容变成一个整数并且我的游戏可以正常运行!
【问题讨论】:
-
您的问题是因为您不知道 GUI 是如何工作的。
Entry不像input()那样工作 - 它不会等待用户的文本和Entry()之后的所有代码在开始时执行,当 Entry 为空时,因此 int() 尝试转换空字符串。您可能需要Button,它会在您将文本输入条目并按下按钮时运行代码。 -
@furas 如何添加按钮?
-
现在我看到你使用
getMouse()来停止代码,所以也许你不必使用按钮。但是,如果您将文本放入 Entry 并尝试将其转换为整数 -int("Hello"),那么您可能会收到错误消息。您必须使用try/except来捕获此错误。 -
您不必在同一个地方创建新条目。您可以清除现有条目 -
textEntry.setText('')
标签: python python-3.x zelle-graphics