【问题标题】:Python 3 - How to input data without pressing <return> in OSXPython 3 - 如何在 OSX 中不按 <return> 输入数据
【发布时间】:2012-02-01 20:44:29
【问题描述】:

我试图在游戏中使用“asdw”键移动角色,但我找不到不按回车键不断输入数据的方法。我已经看到在 windows 上有一个名为 msvcrt 的模块,它有一个 getch 功能,所以我想知道是否有办法在 OSX 中模拟这个,或者更简单地只是不断地从键盘输入数据。

【问题讨论】:

标签: input python-3.x return


【解决方案1】:

您可以使用 Turtle 执行以下操作:

import turtle
Sc = turtle.Screen()
Sc.setup(width=0, height=0)         #this hides turtle's windows
def a():                            #that's the function that you want to run when the key is pressed
    #code here
    Sc.listen()                         #this tells the program to listen 
    for a keypress
    Sc.onkey("#The key here", #the function call here) #this tells the program

按下某个键时调用什么函数

# An example of pressing the key "w"
Sc.onkey("w", a)

【讨论】:

  • 如果评论有点乱,我很抱歉,但这是我第一次真正在stackoverflow上写东西
  • 请学会格式化你的问题,特别是代码。您可以使用三个反引号或缩进块来格式化代码。还有方便的帮助按钮:)
【解决方案2】:

试试curses 库:

http://docs.python.org/py3k/library/curses.html

Curses 是一个用于控制终端的库,它还包括绘制框形状等功能。它适用于任何与 POSIX 兼容的系统,包括 Mac OS X 和 GNU/Linux。

这是一个例子:

import curses
import time

# Turn off line buffering
curses.cbreak()

# Initialize the terminal
win = curses.initscr()

# Make getch() non-blocking
win.nodelay(True)

while True:
    key = win.getch()
    if key != -1:
        print('Pressed key', key)
    time.sleep(0.01)

【讨论】:

  • 出于好奇,您使用的是什么图形库?如果你使用的是专为编写游戏而设计的东西,它应该内置某种键盘系统。顺便说一句,如果你想要图形和交互性,pygame (pygame.org) 很棒。
  • 这是我们在学校课堂上使用的图形库。使用这个游戏不是很好,所以我应该考虑使用pygame。这是模块的链接。 mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html
猜你喜欢
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 2010-10-28
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多