CodeHS环境下非箭头键(如E键)的按键检测问题求助
在CodeHS中检测非箭头按键(如E键)的解决方法
核心问题分析
你当前代码里检测E键的写法if e.key == "E"不生效,是因为CodeHS的按键事件对象中,字母键的key属性值是小写字符串,对应E键的是"e"而非"E"。
修正后的按键检测代码
同时清理代码里的语法错误(多余的反引号、无参数的无效回调),修正后的完整代码如下:
from browser import timer cursor = Rectangle(10, 20) screen = [] textlist = [] boole = [True] username = "EDOS" def init_screen(): background = Rectangle(get_width(), get_height()) screen.append(background) txt = Text("Welcome to EdOS") txt.set_font("12pt Courier New") txt.set_color(Color.white) txt.set_position(0, 12) usertext = Text(f"{username}@EdPC:/$") usertext.set_font("10pt Courier New") usertext.set_position(0, get_height() - 10) usertext.set_color(Color.white) screen.append(usertext) screen.append(txt) print(screen) def add_screen(): screen_copy = screen.copy() for i in range(len(screen_copy)): add(screen_copy[i]) if type(screen_copy[i]) == Text: item = screen_copy[i] screen.remove(item) textlist.append(item) def init_text_input(): cursor.set_color(Color.white) cursor.set_position(get_width() / 5 + 15, get_height() - 25) add(cursor) def blink_cursor(boole): if boole[0]: cursor.set_color(Color.white) else: cursor.set_color(Color.black) def timer_to_blinker(): boole[0] = not boole[0] blink_cursor(boole) def input_handler(e): if e.key == "ArrowLeft": print("Left Arrow key pressed.") if e.key == "ArrowRight": print("Right Arrow key pressed.") if e.key == "ArrowUp": print("Up Arrow key pressed.") if e.key == "ArrowDown": print("Down Arrow key pressed.") # 改为小写的"e"匹配 if e.key == "e": print("E key pressed.") def kernel(): init_screen() add_screen() init_text_input() init_text_input() timer_id = timer.set_interval(timer_to_blinker, 500) kernel() add_key_down_handler(input_handler)
额外实用技巧
- 若不确定其他按键的正确标识,可以在
input_handler中添加print(e.key)语句,按下目标按键后查看控制台输出的字符串值。 - CodeHS的按键事件遵循简化版DOM KeyboardEvent标准:字母键统一返回小写字符串,特殊键(如回车、空格)使用标准名称(如
"Enter"、"Space")。
内容的提问来源于stack exchange,提问作者Soldrion
相关产品推荐
相关产品推荐

