Python 我可以在没有getch()函数的情况下在ncurses屏幕上显示字符串吗?

Python 我可以在没有getch()函数的情况下在ncurses屏幕上显示字符串吗?,python,ncurses,Python,Ncurses,目前,我只知道使用ncurses库显示字符串的一种方法,如下所示: import curses stdscr = curses.initscr() stdscr.addch(0,0,'x') stdscr.getch() 但是我遇到了一个问题,当我想做一个字符串的下降函数时 import curses import time stdscr = curses.initscr() y=1 def fall(): global y stdscr.addstr(y,0,'x')

目前,我只知道使用ncurses库显示字符串的一种方法,如下所示:

import curses

stdscr = curses.initscr()
stdscr.addch(0,0,'x')
stdscr.getch()
但是我遇到了一个问题,当我想做一个字符串的下降函数时

import curses
import time

stdscr = curses.initscr()
y=1
def fall():
    global y
    stdscr.addstr(y,0,'x')
    stdscr.move(y-1,0)
    stdscr.clrtoeol()
    y += 1 
    stdscr.getch()

while True:
    time.sleep(0.2)
    fall()
如果删除此
getch()
函数,我将看不到ncurses屏幕。但如果我把它放进去。我得按一下键盘上的某个键,然后绳子就会掉下来

有没有一种方法可以使字符串在不点击键盘或鼠标的情况下自动落下?

您必须通过调用窗口上的方法(
stdscr
在您的示例中)或通过调用来显式更新屏幕


这是因为诅咒是多年前编写的,当时终端速度非常慢,有效地进行修改非常重要。通过显式更新,您可以先更改屏幕,然后在单个操作中进行更新,而不是对每个操作进行更新。

在您希望在屏幕上反映更改的位置进行刷新。 我不是在纠正,而是在前面的回答中修改了,在我自己的代码下面使用了curses库(添加了注释,以便对新手有所帮助):

一次迭代的快照排序:

两次迭代:

from curses import *
import random, time 
def main(stdscr):
  start_color() # call after initscr(), to use color, not needed with wrapper 
  stdscr.clear() # clear above line. 
  stdscr.addstr(1, 3, "Fig: RAINING", A_UNDERLINE|A_BOLD)
  # init some color pairs:    
  init_pair(10, COLOR_WHITE, COLOR_WHITE) # BG color
  init_pair(1, COLOR_RED, COLOR_WHITE)
  init_pair(2, COLOR_BLUE, COLOR_WHITE)
  init_pair(3, COLOR_YELLOW, COLOR_WHITE)
  init_pair(4, COLOR_MAGENTA, COLOR_WHITE)
  init_pair(5, COLOR_CYAN, COLOR_WHITE)
  # First draw a white square as 'background'
  bg  = ' '  # background is blank 
  for x in range(3, 3 + 75): # horizontal c: x-axis
    for y in range(4, 4 + 20): # vertical r: y-axis
      stdscr.addstr(y, x, bg, color_pair(10))
  stdscr.refresh()  # refresh screen to reflect 
  stdscr.addstr(28, 0, 'Press Key to exit: ')
  # Raining   
  drop = '#' # drop is # 
  while True: # runs infinitely 
    xl = random.sample(range(3, 3+75), 25) # generate 25 random x-positions
    for y in range(5, 4 + 20): # vertical 
      for x in xl:
        stdscr.addstr(y-1, x, bg, color_pair(10)) #clear drops @previous row
        stdscr.addstr(y, x, drop, color_pair(random.randint(1, 5)))
      stdscr.refresh() # refresh each time,  # ^^ add drops at next row
      time.sleep(0.5)  #sleep for moving.. 
    for x in xl: # clear last row, make blank  
      stdscr.addstr(23, x, ' ', color_pair(10))
  stdscr.getkey() # it doesn't work in this code
wrapper(main) #Initialize curses and call another callable object, func,