curses window.getstr()

时间:2014-02-02 01:15:36

标签: python windows curses

我正在尝试在Windows XP上学习Python的curses。我可以让window.getkey命令正常工作,但命令window.getstr不仅失败,而且程序退出。以下是示例代码行:

x = window.getkey()  # this works
y = window.getstr()  # this fails

显然,为了让第一行工作,我已经正确导入了curses并完成了stdscr = curses.initscr()命令。我的窗口已定义并正在运行。我已经尝试将窗口坐标放在getstr parens中,我已经使用了window.move。两者都不起作用。

为什么gettr的任何想法都不起作用?

以下是第一个建议后的更多信息:

首先,在命令提示符窗口而不是桌面上运行程序的建议是好的,因为窗口确实在消失。

这是整个程序:

# program = testcurses
import curses
stdscr = curses.initscr()

window = stdscr.subwin(23,79,0,0)
window.box()
window.refresh()
window.addstr(2,10, "This is my line of text")
window.addstr(4,20,"What happened? ")
window.refresh()

mykey = window.getkey(5,20)
mystr = window.getstr (6,20)
#window.addstr (7,1, "Key data should be here: ")
#window.addstr (7,33, mykey)
window.addstr (8,1, "Str data should be here: ")
window.addstr (8,33,mystr)
window.refresh()

我评论了与关键数据显示相关的行,因为它可以正常工作。

以下是Traceback消息的相关部分:

window.addstr(8,33,mystr) TypeError:必须是str,而不是bytes。

汤姆

1 个答案:

答案 0 :(得分:1)

回溯告诉您,变量mystr是字节对象而不是字符串。这意味着您必须首先对其进行解码,然后才能将其用作addstr()所需的字符串。

以下是您需要做出的更改:

mystr = window.getstr(6,20).decode(encoding="utf-8")

这只是一个Python 3问题!我也用Python 2.7对它进行了测试,没有这个改变。问题出现是由于Python 2和3之间的字节/字符串处理不同。我假设您在使用py3的同时遵循了py2教程。