【问题标题】:Curses keypad(True) does not get special keys诅咒键盘(真)没有得到特殊键
【发布时间】:2017-08-02 20:20:23
【问题描述】:

我正在尝试为 Python 2 和 3 编写代码。这是我用来学习诅咒的完整代码:

# -*- coding: utf-8 -*-
from __future__ import print_function

import curses
import sys
import traceback


class Cursor(object):
    def __init__(self):
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(True)

    def end_window(self):
        curses.nocbreak()
        self.stdscr.keypad(False)
        curses.echo()
        curses.endwin()

    def start_win(self, begin_x=0, begin_y=1, height=24, width=71):
        return curses.newwin(height, width, begin_y, begin_x)


def applic():
    print("yo man")
    x = Cursor()
    window = x.start_win()
    try:
        # This raises ZeroDivisionError when i == 10.
        for i in range(0, 11):
            v = i - 10
            key = window.getch()
            # EDIT - Added this debug line to verify what key gets
            window.addstr('type of {} is {}\n'.format(key, type(key)))
            if key == curses.KEY_UP:
                return
            window.addstr('10 divided by {} is {}\n'.format(v, 10 // v))
            window.refresh()

    except Exception:
        x.end_window()
        errorstring = sys.exc_info()[2]
        traceback.print_tb(errorstring)

applic()

我的问题是key 永远不会等于curses.KEY_UP,因为 getch()(或 getkey())返回的是单个字符串,而不是等于 KEY_UP (\x1b]A) 的整个转义键代码。所以每次我在例程中按向上箭头,程序就会循环通过三个部分的键码\x1b[A,并产生三行输出:

10 divided by -10 is -1
10 divided by -9 is -2
10 divided by -8 is -2

对于这个测试,我希望向上箭头键允许我在 i 等于 10 时发生的预期异常之前突破。

根据 Curses 的 python 文档,stdscr.keypad(True) 应该允许返回整个关键代码,但似乎没有这样做。

添加了一些调试打印输出信息以显示返回的内容。无论我使用 getch() 还是 getkey(),结果都是一样的;它返回一个字符串(文档表明将为 getch 返回一个整数):

type of ^[ is <class 'str'>
10 divided by -9 is -2
type of [ is <class 'str'>
10 divided by -8 is -2
type of A is <class 'str'>
10 divided by -7 is -2

【问题讨论】:

    标签: python-2.7 python-3.x linux-mint python-curses


    【解决方案1】:

    问题是您在主窗口上设置了keypad 属性,但正在使用getch 从不同的窗口读取。此更改将使您的程序接受KEY_UP

    --- curses-vs-keypad.py 2017/04/02 11:07:41     1.1
    +++ curses-vs-keypad.py 2017/04/03 00:57:16
    @@ -28,6 +28,7 @@
         print("yo man")
         x = Cursor()
         window = x.start_win()
    +    window.keypad(True)
         try:
             # This raises ZeroDivisionError when i == 10.
             for i in range(0, 11):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      相关资源
      最近更新 更多