为什么我的if语句不起作用?(图形.py相关的)

2024-10-04 03:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个小程序&我正在尝试检查用户是否输入了我希望他们输入的内容——他们只应键入以下内容之一:快乐、悲伤、愤怒、紧张,兴奋但由于某种原因,它忽略了整个if语句,甚至我绘制的表(矩形)也没有出现?你知道吗

 from graphics import *
 win = GraphWin("Moods", 800, 500)

 #Creating the input Box + A Go Button.
 inputBox=Entry(Point(400,250),12)
 inputBox.draw(win)
 colour=inputBox.getText().lower()

 message=Text(Point(400,50),"Click to go next!")
 message.setFace('courier')
 message.setSize(20)
 message.draw(Win)
 submsg1=Text(Point(400,100),"")
 submsg1.setText("(Allowed moods are: Happy, Sad, Angry, Nervous, 
 Excited)")
 submsg1.setFace('courier')
 submsg1.setSize(15)
 submsg1.setStyle('italic')
 submsg1.draw(win)

 clickPoint = win.getMouse()

 #Checking user inputs the right way.
 if not colour.isalpha():
   error=Text(Point(400,300),"Please type either: happy, sad, angry") 
   error.draw(win)
 elif (colour !="happy" or colour !="sad" or colour !="angry"):  
  error=Text(Point(400,300),"Please type either: happy, sad, angry")
  error.draw(win)
 else:
  #Clearing Second Frame, for next screen.
  inputBox.undraw()
  goButton.undraw()
  error.undraw()
  message.undraw()
  submsg1.undraw()

  #Moving to next frame.
  table=Rectangle(Point(50,400),Point(750,400))
  table.setFill("blue")
  table.draw(win)

Tags: textmessagetableerrorwinnextpointhappy
2条回答

基本上你的代码是这样的:

elif (colour !="happy" or colour !="sad" or colour !="angry"):

由于or的工作方式,如果其中一个条件为true,则将执行此操作。因为其中一个永远是真的(因为用户不能同时输入happy和sad)。你知道吗

因此,对于您的示例,您需要and函数,因为所有条件都必须为true才能运行。你知道吗

elif (colour !="happy" and colour !="sad" and colour !="angry"):

现在要结束,您需要将这一行colour=inputBox.getText().lower()移到这一行clickPoint = win.getMouse()的下面,但在if之前,因为getText是一个在您调用它时执行的事件,所以在您在开始调用它时,没有得到任何结果,因为用户还没有输入任何内容。你知道吗

所以它应该是这样的

clickPoint = win.getMouse()
colour=inputBox.getText().lower()
#Checking user inputs the right way.
if not colour.isalpha():

而不是

elif (colour !="happy" or colour !="sad" or colour !="angry"): 

使用

elif (colour !="happy" and colour !="sad" and colour !="angry"):

and而不是or),因为您的原始条件总是满足的。你知道吗

相关问题 更多 >