0

我正在尝试编写的程序将“Hello World”打印到窗口中。

当用鼠标单击 Hello World 时,它会逐个字符地读取 Hello World

然后将光标向下移动到屏幕下方,并应显示它已读取的内容。

实际显示的是乱码。

Hello world





          ^[[M %!^[[M#%!

它应该是:

Hello world





      Hello world

代码如下所示:

我只是逐个字符地读取字符串,因为我找不到读取整个字符串的方法。

import curses

# Initialize variables
q = -1
stdscr = curses.initscr()
curses.mousemask(1)
curses.start_color()

# color pair 1 = red text on white background
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
stdscr.bkgd(' ', curses.color_pair(1))
stdscr.addstr( "Hello world", curses.color_pair(1) )

# Move cursor furthur down screen and slightly to the right
stdscr.move(10,10)

while True:
  event = stdscr.getch()
  if event == ord('q'):
    break                    # quit if q is pressed

  if event == curses.KEY_MOUSE:
    _, mx, my, _, _ = curses.getmouse()
    y, x = stdscr.getyx()    # put cursor position in x and y


    # read the line character by character into char array called mystr
    mystr = []
    for i in range(140):
      mystr.append(stdscr.inch(my, i))  # read char into mystr
    stdscr.addstr(y, x, "".join(mystr))   # Try to display char array
                                        # but it's garbled
  stdscr.refresh()
curses.endwin()
4

1 回答 1

1

在您的示例中,有两个问题:

  • 您没有调用键盘功能;除非您打开它,否则事件是单字节,而不是功能键
  • inch 函数不是从屏幕获取数据的唯一方法,并且像这样在循环中调用它会引发异常。

这是一个重新设计的示例(它添加了一些功能,例如 ^L 重新绘制屏幕,​​并显示在标题行中读取的文本):

import curses

def hello_world():
  stdscr.erase()
  stdscr.addstr(curses.LINES / 2,
                curses.COLS / 2 - 5,
                "Hello world",
                curses.color_pair(1) )
  
def show_event(event):
  y, x = stdscr.getyx()    # save cursor position
  stdscr.addstr(1,0, "event:" + str(event) + ", KEY=" + curses.keyname(event))
  stdscr.clrtoeol()
  stdscr.move(y, x)

# Initialize variables
q = -1
stdscr = curses.initscr()
stdscr.keypad(1)
curses.mousemask(1)
curses.start_color()

# color pair 1 = red text on white background
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
stdscr.bkgd(' ', curses.color_pair(1))
hello_world()

# Move cursor furthur down screen and slightly to the right
stdscr.move(10,10)

while True:
  event = stdscr.getch()

  if event == 12:
    y, x = stdscr.getyx()    # put cursor position in x and y
    hello_world()
    stdscr.move(y, x)

  if event == ord('q'):
    break                    # quit if q is pressed

  if event == curses.KEY_MOUSE:
    _, mx, my, _, _ = curses.getmouse()

    mystr = stdscr.instr(my, mx) # read remainder of line
    stdscr.addstr(my, mx, "*") # mark where the mouse event occurred
    stdscr.addstr(0, 0, str(my) + "," + str(mx) + " {" + mystr.rstrip() + "}")
    stdscr.clrtoeol()
    stdscr.move(my, mx)

  show_event(event)
  stdscr.refresh()
curses.endwin()

于 2015-03-08T22:56:51.447 回答