def start_monitor(): mon = Monitor() # 监听space按下 keyboard.on_press_key("space", mon.key_down_callback, suppress=True) # 监听space释放 keyboard.on_release_key("space", mon.key_up_callback, suppress=True) keyboard.wait()
def wait_for_input(self): time.sleep(1) keyboard.on_release_key('up', self.input_callback) keyboard.on_release_key('down', self.input_callback) keyboard.on_release_key('left', self.input_callback) keyboard.on_release_key('right', self.input_callback) keyboard.on_release_key('enter', self.input_callback)
def io_response(self): '''override io_response''' resp = int(sample_orientation(n_sample=1, uniform=True)) self.prob.setOri(resp) # global variable for recording response self.resp_flag = True self.increment = 0 # define callback function for keyboard event def left_callback(event): self.increment = -1.0 def right_callback(event): self.increment = +1.0 def release_callback(event): self.increment = 0.0 def confirm_callback(event): self.resp_flag = False def aboard_callback(event): self.resp_flag = False self.win.close() core.quit() # key binding for recording response key_bind = { 'left': left_callback, 'right': right_callback, 'space': confirm_callback, 'escape': aboard_callback } for key, callback in key_bind.items(): keyboard.on_press_key(key, callback) for key in ['left', 'right']: keyboard.on_release_key(key, release_callback) # wait/record for response while self.resp_flag: if not self.increment == 0: resp += self.increment resp %= 180 self.prob.setOri(resp) self.prob.draw() self.fixation.draw() self.win.flip() keyboard.unhook_all() return resp
def bind_keys(self): keyboard.unhook_all() for key in self.parsed_binds: keyboard.on_press_key(key, self._on_press_key, True) keyboard.on_release_key(key, self._on_release_key, True) keyboard.block_key("escape") keyboard.block_key("tab") keyboard.block_key(".") # Prevent windows emoji menu. keyboard.block_key("=") # Prevent windows magnifier. keyboard.block_key("e") # Prevent windows explorer. keyboard.block_key("q") # Prevent windows search.
def main(): cmr = cam() cmr.active = False cmr.camera.resolution = (3280, 2464) cmr.camera.shutter_speed = 400 cmr.led.on() pwrLed = LED(14) pwrLed.on() keyboard.on_release_key('home', lambda _: TakePhoto(cmr)) input("Press enter to quit.")
def io_wait(self, wait_key='space'): '''override io_wait''' self.resp_flag = True def confirm_callback(event): self.resp_flag = False # register callback, wait for key press keyboard.on_release_key(wait_key, confirm_callback) while self.resp_flag: self.win.flip() keyboard.unhook_all() return
def main(pong_game, led_wall, shared_vars): keyboard.on_press_key( 'w', lambda _: pong_game.left_player.paddle.startUpwardMovement()) keyboard.on_release_key( 'w', lambda _: pong_game.left_player.paddle.stopMovement()) keyboard.on_press_key( 's', lambda _: pong_game.left_player.paddle.startDownwardMovement()) keyboard.on_release_key( 's', lambda _: pong_game.left_player.paddle.stopMovement()) keyboard.on_press_key( 'up', lambda _: pong_game.right_player.paddle.startUpwardMovement()) keyboard.on_release_key( 'up', lambda _: pong_game.right_player.paddle.stopMovement()) keyboard.on_press_key( 'down', lambda _: pong_game.right_player.paddle.startDownwardMovement()) keyboard.on_release_key( 'down', lambda _: pong_game.right_player.paddle.stopMovement()) pause_game_due_to_new_ball_init = True while not shared_vars.kill_threads: # pause if ball was freshly initialized or a goal was just scored if pause_game_due_to_new_ball_init: pong_game.delayBallUpdate(1) pause_game_due_to_new_ball_init = False refreshGameScreen(led_wall, pong_game) # update game result = pong_game.update() if result is not None: # goal was scored pause_game_due_to_new_ball_init = True
def __init__(self): self.done = False signal.signal(signal.SIGINT, self.cleanup) # keyboard.hook(self.my_on_key_event) self.f_pressed = False self.d_pressed = False keyboard.on_press_key('f', self.f_down) keyboard.on_release_key('f', self.f_up) keyboard.on_press_key('d', self.d_down) keyboard.on_release_key('d', self.d_up) while not self.done: time.sleep(1) # Wait for Ctrl+C
def make_keybinds(): keyboard.on_press_key('w', drive_forward) keyboard.on_release_key('w', stop_chassis) keyboard.on_press_key('s', drive_backward) keyboard.on_release_key('s', stop_chassis) keyboard.on_press_key('a', rotate_left) keyboard.on_release_key('a', stop_chassis) keyboard.on_press_key('d', rotate_right) keyboard.on_release_key('d', stop_chassis)
def run(self): # Reset talk release self.talk_release_is_pending = False # Create audio streams input_stream = DeviceInputStream(self.input_device) output_stream = DeviceOutputStream(self.output_device) if self.playback_device != None: playback_stream = DeviceOutputStream(self.playback_device) if self.enable_burst: keyboard.on_release_key(self.talk_key, self.handle_release_talk, suppress=True) # Run voice changer while self.is_active: talk_is_active = keyboard.is_pressed(self.talk_key) burst_is_active = self.enable_burst and talk_is_active == False and ( time.time() - self.last_talk_release_time ) < self.burst_sound.duration_seconds audio_is_active = talk_is_active or burst_is_active keyboard_needs_release = self.talk_release_is_pending and burst_is_active == False elapsed = time.time() - self.start_time if audio_is_active: # Get sound from microphone sound = input_stream.read(self.chunk_size) # Add overlays and transformations sound = (sound + 15).equalize().overlay_using_start_time( self.static_sound - 25, elapsed % self.static_sound.duration_seconds) if (burst_is_active): sound = sound.overlay_using_start_time( self.burst_sound - 5, time.time() - self.last_talk_release_time) # Play if self.playback_device != None: playback_stream.play(sound) output_stream.play(sound) elif keyboard_needs_release: # Trigger delayed talk key release keyboard.release(self.talk_key) self.talk_release_is_pending = False
def __init__(self, key, callback): self.presshandler = None self.releasehandler = None self.callback = callback self.pressed = False self.presshandler = on_press_key(key, self.press, True) self.releasehandler = on_release_key(key, self.release, True)
def main(): on_release_key('w', w_callback) on_release_key('s', s_callback) on_release_key('a', a_callback) on_release_key('d', d_callback) try: while True: sleep(60) except KeyboardInterrupt: pass
def key_wait(self, keys): # wait on multiple keys # B and Y for scanner two button box self.wait_flag = True def confirm_callback(event): self.wait_flag = False # register callback for key in keys: keyboard.on_release_key(key, confirm_callback) # wait for key press while self.wait_flag and self.exp.exp_run: time.sleep(0.01) keyboard.unhook_all() return
def __init__(self, *args, **kwargs): super(Parametrage, self).__init__(*args, **kwargs) self.settings = App.get_running_app().config self.font = ".\\assets\\seguisym.ttf" self.mode = self.settings.get('hidden', 'starting') # Stores the current mode self.portDropDown = MenuDropDown() self.fileDropDown = MenuDropDown() self.undoRedo = UndoRedo() self.arduino = Arduino(self.settings, self.easyPopup, self.update_rect, programs={ "Direct": {"isDirectProgram": True, "path": osJoinPath(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + os.pardir), "directFile\\directFile.ino")}, "Current": {"isDirectProgram": False, "path": osJoinPath(os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + os.sep + os.pardir), "currentFile\\currentFile.ino")}}) self.imageWidth = float(self.settings.get('hidden', 'imWidth')) # in meter self.imageHeight = float(self.settings.get('hidden', 'imHeight')) # in meter self.actualWidth = float(self.settings.get('hidden', 'acWidth')) # in meter self.actualHeight = float(self.settings.get('hidden', 'acHeight')) # in meter self.imageOrigin = make_tuple(self.settings.get('hidden', 'origin')) # in cm self.popup = -1 # Specific to the mode 'Pipe' self.pipePanel = self.ids.tuyeauInputs self.gaps = [] # Specific to the mode 'Free' self.lineWidth = float(self.settings.get('colors', 'lineWidth')) self.diametre = float(self.settings.get('colors', 'nodeDiam')) self.isDragging = -1 self.lastTouched = -1 self.zoomFactor = 1 self.innerScreenMargin = [-self.diametre/2-5, self.diametre/2+5, self.diametre/2+25, -self.diametre/2-25] # Left, Right, Top, Down self.corners = [(88, 82), (88, -72), (-75, 82), (-75, -72)] # Right-Top, Right-Down, Left-Top, Left-Down # Specific to the mode 'direct' self.switchDiameter = float(self.settings.get('colors', 'switchDiam')) Clock.schedule_once(self.binding) Clock.schedule_interval(lambda a: self.save(-1, -1), int(self.settings.get('general', 'autoSave')*60)) keyboard.on_release_key(self.settings.get('shortcuts', 'corner'), self.update_rect)
def run(args: argparse.Namespace): piano = Piano(args.config['awg'].get('address')) for key in NOTE_KEYS: keyboard.on_press_key(key, lambda event: piano.play_note(NOTE_KEYS.get(event.name)), suppress=True) keyboard.on_release_key(key, lambda event: piano.release_note(NOTE_KEYS.get(event.name)), suppress=True) for key in map(str, range(0, 10)): keyboard.on_press_key(key, lambda event: _set_octave(piano, event.name), suppress=True) keyboard.on_press_key('c', lambda event: _stop(piano), suppress=True) keyboard.on_press_key('n', lambda event: piano.next_wave(False), suppress=True) keyboard.on_press_key('m', lambda event: piano.next_wave(True), suppress=True) LOGGER.info('Keys: c = exit, n,m = select waveform, 0-9 = octave') LOGGER.info(", ".join([f"{key}={note}" for key, note in NOTE_KEYS.items()])) while piano.is_alive(): time.sleep(1) sys.stdin.readline() # Clear buffer LOGGER.info('Bye!')
async def run(address, loop): print("Start connecting ...") async with BleakClient(address, loop=loop) as client: print("Connect!", end="\n\n") key_used = sorted(set(press_keycmd_map.keys()).union(release_keycmd_map.keys())) for key in key_used: keyboard.on_press_key(key, press_put_queue, suppress=True) keyboard.on_release_key(key, release_put_queue, suppress=True) print("Key {} are now ready".format(key_used)) keyboard.add_hotkey('q', set_exit, suppress=True) print("You can now control the robot via BLE UART. (press q to exit)", end="\n\n") while not is_exited: await send(client) print("Disconnected!")
def main(): inter = Interface() world = esper.World() random.seed() creature = {} tree = {} for i in range(15): creature[i] = world.create_entity( Life(), Mind(), Position(random.randint(40, 80), random.randint(10, 50)), Paint(125, 125, 125, 100)) tree[i] = world.create_entity( Life(), Tree(20), Position(random.randint(40, 80), random.randint(10, 50)), Paint(50, 150, 50, 100)) world.add_processor(Show()) world.add_processor(Move()) world.add_processor(Grow()) world.add_processor(Bear_Fruit()) #keyboard.add_hotkey('r', print, args=[world.component_for_entity(user, Relations).relations2others]) keyboard.on_release_key('enter', inter.pause_pressed) # A dummy main loop: try: while True: inter.step_number += 1 inter.step() time.sleep(0.1) world.process() graph.flip() while (inter.pause): pass except KeyboardInterrupt: return
async def run(address, loop): print("Start connecting ...") async with BleakClient(address, loop=loop) as client: print("Connect!", end="\n\n") key_used = ['1', '2', '3', '4', 'up', 'down', 'left', 'right'] for key in key_used: keyboard.on_press_key(key, press_put_queue, suppress=True) keyboard.on_release_key(key, release_put_queue, suppress=True) print("Key {} are now ready".format(key_used)) keyboard.add_hotkey('q', set_exit, suppress=True) print("You can now control the robot via BLE UART. (press q to exit)", end="\n\n") while not is_exited: await send(client) print("Disconnected!")
def enable(self, autorunState, dwarfglitchState): if autorunState: keyboard.on_press_key(self.hkAutorun, lambda e: self.switch_mode()) keyboard.on_release_key('w', lambda e: self.stop('w')) keyboard.on_release_key('shift', lambda e: self.stop('shift')) keyboard.on_release_key('s', lambda e: self.stop('s')) if dwarfglitchState: keyboard.add_hotkey(self.hkDwarfglitch, lambda: self.go_dwarf())
def run(self): cap = cv2.VideoCapture(0) keyboard.on_press_key('c', self.on_press) keyboard.on_release_key('c', self.on_release) while cap.isOpened(): ret, self.image = cap.read() self.roi = cv2.cvtColor(self.image[0:self.roi_size, 0:self.roi_size, :], cv2.COLOR_BGR2HSV) if self.calibrate: self.draw_calibration_rects() self.image, roi, mask = self.processor.process_image(self.image, self.roi, self.roi_size, self.lower_skin, self.upper_skin) if self.show_input: cv2.imshow('camera', self.image) if self.show_hsv: cv2.imshow('hsv', roi) if self.show_mask: cv2.imshow('mask', mask) k = cv2.waitKey(10) if k == 27: break cap.release() cv2.destroyAllWindows()
def start_exe(): global actionList global loadState global runState if loadState == 0: messagebox.showinfo("提示", "请上传动作列表文件") elif entry_hotkey.get() == "": messagebox.showinfo("提示", "请输入启动热键") else: if runState == 0: keyboard.on_release_key(entry_hotkey.get(), action_exe, suppress=False) label_state2.config(text="运行中") button_run.config(text="停止") runState = 1 print("run") elif runState == 1: keyboard.unhook_all() label_state2.config(text="已停止") button_run.config(text="运行") runState = 0 print("stop")
def start_hotkeys(self): obs_settings = self.app.settings.hotkeys.obs kivy_settings = self.app.settings.hotkeys.kivy general_settings = self.app.settings.hotkeys.general # Camera Hotkey keyboard.hook_key(obs_settings.camera_scene_hotkey[0], lambda x: self.on_hotkey("camera", x), suppress=True) Logger.info("binding hotkey " + f"{obs_settings.camera_scene_hotkey[0]}") # Center Scene Hotkey keyboard.hook_key(obs_settings.center_screen_hotkey[0], lambda x: self.on_hotkey("center", x), suppress=True) Logger.info("binding hotkey" + f" {obs_settings.center_screen_hotkey[0]}") # Automatic Checkbox Hotkey keyboard.add_hotkey(kivy_settings.scene_lock, lambda x: self.on_hotkey("scene_lock", x), suppress=True) Logger.info(f"binding hotkey {kivy_settings.scene_lock}") # Next Button for the clicker keyboard.on_release_key(general_settings.clicker_forward, lambda x: self.on_hotkey("clicker_next", x), suppress=True) Logger.info(f"binding hotkey {general_settings.clicker_forward}") # Previous Button for the clicker keyboard.on_release_key(general_settings.clicker_backward, lambda x: self.on_hotkey("clicker_prev", x), suppress=True) Logger.info("binding hotkey " + f"{general_settings.clicker_backward}")
def __init__(self, main_title, behaviours): """ :type behaviours list """ self.initial_pos = {'x': 2, 'y': 1} self.behaviour_list = behaviours for behaviour in self.behaviour_list: if not 'callback' in behaviour: self.initial_pos['y'] += 1 else: break self.behaviour_list.append({'main': "Confirm", 'description': "Validate your actions"}) self.key_map_listed = [key for key in self.behaviour_list] self.map_length = len(self.behaviour_list) self.cursor_pos = {'x': 1, 'y': 1} self.offset = {'x': 0, 'y': 1} self.checked_cases = [] # Thread(target=self.wait_key).start() self.callback_todo = [] self.clear_screen() self.move_to(1, 1) for behaviour in self.behaviour_list: # type: dict if 'flags' in behaviour: if 'title' in behaviour['flags']: separator = "-" * 10 print("{2}{0}{1:^20}{0}{3}".format(separator, behaviour['main'], Fore.CYAN, Fore.RESET), end="\n") if 'description' in behaviour: print('[{0:}] {1:} : {2:40}'.format(unchecked_char, behaviour['main'], behaviour['description']), end="\n") self.move_to_first_choice() keyboard.on_release_key('Up', self.upper_action) keyboard.on_release_key('Down', self.downer_action) keyboard.on_release_key('Space', self.space_action) Thread(target=self.prevent_stop).start()
def captureMotion(verbose: bool, channelName: str, out_file: str, sound_file: str): if verbose: print("capturing input to channel name %s. Storing in file %s." % (channel, out_file)) print(INSTRUCTIONS_STRING) keyboard.on_release_key(START_CHAR, startRecordingCallback, suppress=True) keyboard.on_press_key(BEAT_CHAR, startBeatCallback, suppress=True) keyboard.on_release_key(BEAT_CHAR, endBeatCallback, suppress=True) keyboard.on_release_key(END_CHAR, endRecordingCallback) t = threading.Thread(target=writeFile, args=[out_file, channelName, sound_file]) t.start() # keyboard.wait() t.join()
def run(filename): # Create the file as global # so that the keyboard press # handlers may access them global file file = createFile(filename) # Adds headers to the created # file addHeaders() # Show the available keybinds to # the user printKeybinds() # Create global possession # object so that all handlers # may access it global possession possession = {} # Create global quarter integer # so that all handlers may access it global quarter quarter = 1 # Bind the KEYBIND_POSSESSION to its handler keyboard.on_release_key(KEYBIND_POSSESSION, handlePossession) # Bind the KEYBIND_QUARTER to its handler keyboard.on_release_key(KEYBIND_QUARTER, handleQuarter) # Bind all other keybinds for keybind in KEYBINDS: keyboard.on_release_key(keybind, handleKeybind) # while True: keyboard.wait()
def test_on_release_key(self): keyboard.on_release_key( 'a', lambda e: self.assertEqual(e.name, 'a') and self.assertEqual( e.event_type, KEY_UP)) self.do(d_a + u_a)
def test_on_release_key(self): keyboard.on_release_key('a', lambda e: self.assertEqual(e.name, 'a') and self.assertEqual(e.event_type, KEY_UP)) self.do(d_a+u_a)
if(pause > 300 and pause < 500): pyautogui.click(savedCoords[0][0], savedCoords[0][1]) previousTime = timestamp root.after(10, root_loop) class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent w = tk.Label(self, text="HACKATHON BABY") w.pack(); def moveToCurrent(info): global pressed if not pressed: pressed = True pyautogui.moveTo(currX, currY) def click(info): global pressed pyautogui.click() pressed = False if __name__ == "__main__": MainApplication(root).pack(side="top", fill="both", expand=True) root.after(50, root_loop) keyboard.on_press_key('alt', moveToCurrent); keyboard.on_release_key('alt', click); root.mainloop()
def register(self): for k in SCAN_CODES_HID_USAGEID_MAPPING: keyboard.on_press_key(k, self.key_press_handler) keyboard.on_release_key(k, self.key_release_handler)
def pressed_c(f): ui.lab_c.setStyleSheet(str(colorscheme_pressed)) # ---- Init app = QApplication(sys.argv) window = QWidget() ui = Ui_Form() ui.setupUi(window) # ---- Hotkeys # keyboard.add_hotkey('a', set_style_bgwhite) ---- This is a test keyboard.on_press_key('up', pressed_up) keyboard.on_release_key('up', release_up) keyboard.on_press_key('down', pressed_down) keyboard.on_release_key('down', release_down) keyboard.on_press_key('a', pressed_a) keyboard.on_release_key('a', release_a) keyboard.on_press_key('d', pressed_d) keyboard.on_release_key('d', release_d) keyboard.on_press_key('c', pressed_c) keyboard.on_release_key('c', release_c) keyboard.on_press_key('x', pressed_x) keyboard.on_release_key('x', release_x) # ---- Launch Window window.show() sys.exit(app.exec_())
print('Started...') def on_key_press(e): global memory global last_timestamp if not e.name or any(key in e.name for key in reset_keys): return time = e.time timestamp = datetime.fromtimestamp(time) delta = timestamp - last_timestamp if delta.total_seconds() > TIMEOUT: memory = [] memory.append(e) last_timestamp = timestamp def on_alt_release(e): global memory memory = [] keyboard.on_press(on_key_press) keyboard.on_release_key('alt', on_alt_release) keyboard.add_hotkey('ctrl+alt+shift', on_triggered) print("Press TAB+ESC to stop.") keyboard.wait('tab+esc')