How to prevent a keyboard response being detect globally?

Hi,
In my study, I have a section consisted of 2 screens in which participants need to press response keys in the second screen. However, the keyboard object defined in the second screen appears being detected in every frame of the experiment. That is, if pressed in any frame including frames in the first screen, the target keys would be registered as pressed and subsequent keyboard response screen would be skipped. How can I prevent a keyboard response being detect globally?
Thanks in advance.

from psychopy import visual, core
from psychopy.hardware import keyboard

win = visual.Window(fullscr = False, size = (800,600),
                    color = (-1.0,-1.0,-1.0), units = 'norm', monitor = 'testMonitor')

timer=core.Clock()
kb = keyboard.Keyboard()

font_color = 'white'
font_size  = 0.08

text_1 = visual.TextStim(win, text = ' ', height = font_size, pos = (0,0), color = font_color, bold = True)
text_2 = visual.TextStim(win, text = ' ', height = 0.08, pos = (0,0), color = font_color, bold = True)
text_lbelow = visual.TextStim(win, text = 'f', height = font_size, pos = (-0.6,-0.8), color = font_color, bold = True)
text_rbelow = visual.TextStim(win, text = 'j', height = font_size, pos = (0.6,-0.8), color = font_color, bold = True)

def screen_1(time=2):
    text_1.text= 'text 1'
    timer.reset()
    while timer.getTime() < time:
        text_1.draw()
        win.flip()

def screen_2(displayed= 'q1'):
    text_2.text = displayed
    finish = False
    timer.reset()
    while finish == False:
        text_2.draw()
        # allow keyboard response after the text being displayed for 2 seconds
        if timer.getTime() >=2: 
            text_lbelow.draw(); text_rbelow.draw()
            k_estimate = kb.getKeys(['f', 'j'], waitRelease=True)
            for thisKey in k_estimate:
                if thisKey=='f':
                    print('f')
                else:
                    print('j')
                finish = True
        win.flip()

for i in range(5):
    screen_1()
    screen_2()

Keypress events go into a queue so they can be dealt with if your code wasn’t running at the exact time that they occurred. You can filter them out based on their time stamp (i.e. ignore ones that occurred before 2 s into screen 2), or you can explicitly turn the keyboard monitoring on and off by using the .start() and .stop() methods of the keyboard object.

For simplicity, you might just want to use the keyboard’s own clock for timing. That way, the recorded key presses will also have a consistent and meaningful time stamp.