【问题标题】:Problem in code while using Python msvcrt使用 Python msvcrt 时出现代码问题
【发布时间】:2020-03-22 10:01:39
【问题描述】:

只有黑屏,怎么回事?

import msvcrt
while(1):
  choice = msvcrt.getch()
  if(choice =='a'):
      print('a')
  elif(choice =='s'):
      print('s')

【问题讨论】:

  • 我想在不按回车的情况下从用户那里获取单个字符输入
  • 您的代码对我来说看起来不错? oreilly.com/library/view/python-standard-library/0596000960/…
  • 啊,这不是shebang问题吧?
  • @Aiyion.Prime Windows 不知道 shebangs
  • @Aiyion.Prime 您提供的参考资料是一本关于 Python 2 的书。

标签: python python-3.x msvcrt


【解决方案1】:

您的问题是 getch() 返回一个字节而不是字符串。如果按achoice 的值是字节串b'a',它与字符串'a' 不同。考虑一下:

>>> choice = b'a'
>>> choice == 'a'
False
>>> choice.decode() == 'a'
True

你的屏幕仍然是空白的,因为if-condition 都不可能为真,而且你没有包罗万象的else: 子句。只需打印出choice 的值,您就可以自己发现这一点。

更改您的测试
if choice =='a':

if choice.decode() == 'a':

(并从您的 if 测试中删除那些不必要的括号)。

在 Python 2 中,您的原始代码会按照您期望的方式运行。

【讨论】:

    猜你喜欢
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 2017-03-30
    • 2014-02-27
    • 1970-01-01
    相关资源
    最近更新 更多