How do I fix key not found error in python?

Question:

I’m new to coding and I’m trying to write a password manager program here. I decided to use sg.Frame instead of sg.Tab (Which worked just fine but I just don’t like how it looked.) and ran into this problem where it has problem finding the key ‘Login’. What made me confused is I already assigned the key in line 22 or am I doing something wrong? (Which is extremely likely.)

import random
import getpass
import PySimpleGUI as sg

us = '*'
pw = '**'

main_enabled=False

login_layout = [
        [sg.Text('Username'), sg.InputText(do_not_clear=False)],
        [sg.Text('Password'), sg.InputText(do_not_clear=False)],
        [sg.Button('OK')]
    ]

main_layout = [
        [sg.Button('Saved Passwords')],
        [sg.Button('Generate New Password')]
    ]

layout = [
    [sg.Frame('Login', login_layout, visible=True)],
    [sg.Frame('Main', main_layout, visible=False)]
]

window = sg.Window('PWKeep', layout, resizable=True)

while not window.was_closed():
    event, values = window.read()
    if event == 'OK':
        if values[0] == us and values[1] == pw:
            main_enabled=True
            window['Login'].update(visible=False)
            window['Main'].update(visible=True)
        else :
            sg.Popup('Wrong Username or Password. Please Try Again.')

window.close()

Don’t worry about the hardcoded username and password, This program is far from finished as you may already have seen.

I also would love to hear about how I can optimize/improve this program further.

Asked By: laff

||

Answers:

You need to assign the element a key attribute like this:

layout = [
    [sg.Frame('Login', login_layout, visible=True, key='Login')],
    [sg.Frame('Main', main_layout, visible=False, key='Main')]
]

Then you will have window['Login'] and window['Main'] working properly.

Answered By: Alex Bochkarev
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.