python - Tkinter Frame Not Recognizing Keypresses -
this question not duplicate of question: why doesn't .bind() method work frame widget in tkinter?
as can see, set focus current frame in game_frame() method.
i'm writing chip-8 emulator in python , using tkinter gui. emulator running, can't tkinter recognize keypresses. here code:
def game_frame(self): self.screen = frame(self.emulator_frame, width=640, height=320) self.screen.focus_set() self.canvas = canvas(self.screen, width=640, height=320, bg="black") self._root.bind("<keypress-a>", self.hello) key in self.cpu.key_map.keys(): print(key) self.screen.bind(key, self.hello) self.screen.pack() self.canvas.pack() def hello(self, event): if event.keysym in self.cpu.key_map.keys(): self.cpu.keypad[self.cpu.key_map[event.keysym]] = 1 self.cpu.key_pressed = true self.cpu.pc += 2 sys.exit() def run_game(self, event): self.game_frame() self.cpu.load_rom("tank") while true: self._root.update() self.after(0, self.cpu.emulate_cycle)
could please me figure out what's going wrong? think might have game loop interfering key bindings, i'm not sure. hello method never gets called when run game because program continues run in infinite loop , never exits, regardless of key pressed. thank you!
the problem due 2 things. without seeing code it's impossible sure.
for one, binding capital "a" rather lowercase "a" -- have testing binding works or not when press capital a?
also, using after
, update
incorrectly. may starving event loop, preventing processing key presses. right way run function periodically have function (re)schedules itself.
class cpu_class(): ... def run_cycle(self): self.emulate_cycle() self._root.after(1, self.run_cycle)
two things note:
- don't use
after(0, ...)
-- need give tkinter @ least ms or process other events. - the run_cycle function responsible running 1 cycle, , scheduling next cycle run in future.
once that, no longer need while
loop. can call run_cycle
once, , start cpu running.
Comments
Post a Comment