gpt4 book ai didi

python - python中等待输入1秒

转载 作者:行者123 更新时间:2023-12-01 07:53:14 26 4
gpt4 key购买 nike

我正在尝试使用 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秒?

最佳答案

默认情况下,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

关于python - python中等待输入1秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com