Python 3 - 如何在不按的情况下输入数据在操作系统中

发布于 2024-12-23 18:20:53 字数 135 浏览 3 评论 0原文

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

I am attempting to move a character using the "asdw" keys in a game, but I cannot find a way to constantly input data without pressing return. I have seen that on windows there is a module called msvcrt, which has a getch function, so I am wondering if there is a way to simulate this in OSX, or more simply to just constantly input data from the keyboard.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

z祗昰~ 2024-12-30 18:20:53

尝试使用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)

Try the curses library:

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

Curses is a library for controlling the terminal, and includes features such as drawing box shapes as well. It's available on any POSIX-compatible system, which includes Mac OS X and GNU/Linux.

Here's an example:

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)
梦旅人picnic 2024-12-30 18:20:53

您可以使用 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)

You can use Turtle to do something like this:

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

What function to call when a certain key is pressed

# An example of pressing the key "w"
Sc.onkey("w", a)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文