简体   繁体   中英

How to fix Tkinter frames controller key error?

I'm new to python I'm trying to create a login using RFID. I started to create a simple GUI using lots of Toplevel windows, but I want to create a GUI in only one window and the controller solves it. Now I'm having a problem since I'm trying to get the value of a variable "id" and use it as a reference to get data from my database.

Here's my code.

class Kiosk(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        GPIO.setwarnings(False)

        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.style = Style()
        self.style.theme_use('alt')
        self.style.map('TCombobox', fieldbackground=[('readonly','white')])

        self.db = pymysql.connect(host = "192.168.1.11",port = 3306, user = "root",passwd = "justin",db= "thesis_db")
        self.cursor = self.db.cursor()
        self.QueryResident = "CREATE TABLE IF NOT EXISTS residents_db (FIRST_NAME varchar(255) not null, MIDDLE_NAME varchar(255) not null, LAST_NAME varchar(255) not null,SEX varchar(255) not null, BIRTH_DATE date, CIVIL_STATUS varchar(255) not null, PLACE_OF_BIRTH varchar(255) not null, RFID varchar(255) not null)"
        self.cursor.execute(self.QueryResident)

        self.frames = {}
        for F in (Start_Page, Registration_Page_Admin, Registration_Page_User, Update_User, Update_Admin, Login_RFID, main_page):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("Start_Page")

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()
    def get_page(self, page_class):
        return self.frames[page_class]

class Start_Page(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        label = Label(self, text="Login", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = Button(self, text="Login",
                            command=lambda: controller.show_frame("Login_RFID"))
        button1.pack()

class Login_RFID(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.parent = parent
        self.controller = controller
        self.get_Firstn1 = None
        self.img_login = (Image.open("Scan_RFID.png"))
        self.image_login = self.img_login.resize((550,417))
        self.img_background_login = ImageTk.PhotoImage(self.image_login)

        self.db = pymysql.connect(host = "192.168.1.11",port = 3306, user = "root",passwd = "justin",db= "thesis_db")
        self.cursor = self.db.cursor()

        label_login = Label(self, image = self.img_background_login) 
        label_login.pack(fill="both", expand = 1)
        label_login.bind('<Enter>',self.login_RFID)


    def login_RFID(self, event):
        self.reader = SimpleMFRC522()
        self.id, self.text = self.reader.read()
        self.cursor.execute("SELECT * FROM residents_admin WHERE RFID = %s",str(self.id))
        if (self.cursor.fetchone() is not None): 
            self.controller.show_frame("main_page")
            qwe = False
        else:
            self.cursor.execute("SELECT * FROM residents_db WHERE RFID = %s", str(self.id))
            if (self.cursor.fetchone() is not None): 
                self.controller.show_frame("main_page")
                qwe = False
            else:
                messagebox.showerror("Warning!","Your RFID card is not yet registered!")

    def get_data(self):
        self.cursor.execute("SELECT * FROM residents_admin WHERE RFID = %s",str(self.id))
        if (self.cursor.fetchone() is not None): 
            self.cursor.execute("SELECT FIRST_NAME FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Firstn = self.cursor.fetchone()
            self.get_Firstn1 = str(self.get_Firstn[0])
            self.cursor.execute("SELECT MIDDLE_NAME FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Middlen = self.cursor.fetchone()
            self.get_Middlen1 = str(self.get_Middlen[0])
            self.cursor.execute("SELECT LAST_NAME FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Lastn = self.cursor.fetchone()
            self.get_Lastn1 = str(self.get_Lastn[0])
            self.cursor.execute("SELECT BIRTH_DATE FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Birthd = self.cursor.fetchone()
            self.get_Birthd1 = str(self.get_Birthd[0])
            self.cursor.execute("SELECT PLACE_OF_BIRTH FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Placeb = self.cursor.fetchone()
            self.get_Placeb1 = str(self.get_Placeb[0])
            self.cursor.execute("SELECT CIVIL_STATUS FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Civils = self.cursor.fetchone()
            self.get_Civils1 = str(self.get_Civils[0])
            self.cursor.execute("SELECT SEX FROM residents_admin WHERE RFID = %s", str(self.id))
            self.get_Sex = self.cursor.fetchone()
            self.get_Sex1 = str(self.get_Sex[0])

class main_page(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        label = Label(self, text="Welcome", font=controller.title_font)
        label.pack()
        login_rfid_page = self.controller.get_page("Login_RFID")
        login_rfid_page.get_data(None)
        value = login_rfid_page.get_Firstn1
        print(value)

        button1 = Button(self, text="Register User",
                            command=lambda: self.controller.show_frame("Registration_Page_User"))
        button2 = Button(self, text="Register Admin",
                            command=lambda: self.controller.show_frame("Registration_Page_Admin"))
        button3 = Button(self, text="Update User",
                            command=lambda: self.controller.show_frame("Update_User"))
        button4 = Button(self, text="Update Admin",
                            command=lambda: self.controller.show_frame("Update_Admin"))
        button1.pack()
        button2.pack()
        button3.pack()
        button4.pack()

Here's my error.

    Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/pi/Thesis/qweqweqweq.py", line 85, in login_RFID
    self.controller.show_frame("main_page")
  File "/home/pi/Thesis/qweqweqweq.py", line 45, in show_frame
    frame = self.frames[page_name]
KeyError: 'main_page'

I think I don't have any problem scanning my RFID. I just need to get the value of the scanned RFID from id to the main page to use it as a reference to get the required data.

I followed the solution answered by Sir Bryan Oakley here and to his other answers to other questions. I read it all night, I somehow get what he meant to his answer I just don't know why I can't do it.

I hope you guys can help me. I trimmed the code above and provided the only code related to the error. Thank you!

First: you have to use self.id instead of id to have access to id from different places

def login_RFID(self, event):

    self.reader = SimpleMFRC522()
    self.id, self.text = self.reader.read()  # self.id

Second: you would have to run this function in main_page to get correct value

    login_rfid_page = self.controller.get_page("Login_RFID")

    login_rfid_page.login_RFID(None)  # run scanner

    value = login_rfid_page.id
    print(value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM