首页 > 解决方案 > 在python中等待输入1秒

问题描述

我正在尝试使用 curses 在 Python 中制作一个笔记应用程序。左下角应该是一个每秒更新的时钟。

我现在遇到的问题是它要么必须休眠 1 秒,要么等待输入。

如果没有注册输入,是否可以等待输入 1 秒并继续?

我想这样做的原因是为了防止在应用程序中移动时出现延迟。

我在想像多线程这样的东西可以完成这项工作,但也有一些问题。

这是我到目前为止的代码:

#!/usr/bin/env python3
import curses
import os
import time
import datetime
import threading


def updateclock(stdscr):
    while True:
        height, width = stdscr.getmaxyx()
        statusbarstr = datetime.datetime.now().strftime(' %A')[:4] + datetime.datetime.now().strftime(' %Y-%m-%d | %H:%M:%S')
        stdscr.addstr(height-1, 0, statusbarstr)

        time.sleep(1)

def draw_menu(stdscr):
    k = 0

    stdscr.clear()
    stdscr.refresh()

    threading.Thread(target=updateclock, args=stdscr).start()

    cursor_y = 0
    cursor_x = 0

    while (k != ord('q')):
    #while True:

        stdscr.clear()
        height, width = stdscr.getmaxyx()

        stdscr.addstr(height//2, width//2, "Some text in the middle")

        if k == curses.KEY_DOWN:
            cursor_y = cursor_y + 1
        elif k == curses.KEY_UP:
            cursor_y = cursor_y - 1
        elif k == curses.KEY_RIGHT:
            cursor_x = cursor_x + 1
        elif k == curses.KEY_LEFT:
            cursor_x = cursor_x - 1

        stdscr.refresh()
        #time.sleep(1)

        # Wait for next input
        k = stdscr.getch()


curses.wrapper(draw_menu)

代码看起来很乱,这是我第一次主要关注 curses 函数。

是否可以只等待输入k = stdscr.getch()1 秒?

标签: pythoncurses

解决方案


默认情况下,getch 将阻塞,直到您准备好字符输入。如果 nodelay 模式为 True,那么您将获得准备好的字符的字符值 (0-255),或者您将获得 -1 表示没有准备好字符值。

stdscr.nodelay(True) #Set nodelay to be True, it won't block anymore
k = stdscr.getch() #Either the next character of input, or -1

推荐阅读