unbenannt
unbenannt

Reputation: 11

How can I trigger a key event only after another key event has been triggered?

I am a student learning Python, it would be great if you guys can help me out with this.

This is a temporary minimum code segment, window1 is a premade variable that creates a rectangle outside the function.

def key_pressed(event):
    if event.key == "a":
        add(window1)
    else:    
        if event.key == "n":
            name = str(input("Task Name: "))
            tname = Text(name)
            tname.set_position(get_width(), get_height())
            add(tname)              
        elif event.key == "t":
            time = int(input("Due Time: "))
            ttime = Text(str(time))
            add(tname)
    if event.key == "Escape":
        remove(window1)
        remove(tname)
        remove(ttime)

add_key_down_handler(key_pressed)

etc.etc.

I'm using Python 3 Graphics (Brython) on the website CodeHS, and I want my program to allow a key event only after another one has been pressed. I've tried nesting the if statements and other stuff but I can't seem to get it to work. Plus, the event.key == "Escape" does not remove the tname and ttime graphics.

How can I make it so that 'n' and 't' can only be pressed after 'a' is pressed and not be pressed after 'esc' when it removes the window?

Thanks

Upvotes: 1

Views: 301

Answers (1)

shreya
shreya

Reputation: 1

I'm also a student (also doing CodeHS currently) and I tried to figure out a way to solve this. Here's an edited version of your code (replace the "A SUCCESSFUL" message with your own code, but since I didnt have a window1 I decided to use a simple "print" function instead).

has_a_yet = False

def callback(event):
    key = event.key
    print([key])
    
if key == 'a':
    print("A SUCCESSFUL")
    has_a_yet = True
    
if has_a_yet:
    if key == "n":
        name = str(input("Task Name: "))
        tname = Text(name)
        tname.set_position(get_width(), get_height())
        add(tname)              
    elif key == "t":
        time = int(input("Due Time: "))
        ttime = Text(str(time))
        add(tname)

if key == "Escape":
    print("remove all objects")

add_key_down_handler(callback)

Upvotes: 0

Related Questions