Python Tkinter 窗口未在窗口屏幕上居中且按钮浮雕不起作用

发布于 2025-01-10 07:57:05 字数 25823 浏览 2 评论 0原文

这是我在 python 上使用 tkinter 的带有注册表单和更改密码表单的登录页面的代码。我无法将主显示窗口置于计算机屏幕中央。这是我的代码的底部。我不知道如何解决这个问题。按钮格式(例如浮雕样式)也不起作用。如果对我的代码有任何问题或建议,请告诉我,我们将不胜感激!

编辑:背景颜色现在显示在显示屏上。

'''

import tkinter as tk
from tkinter import messagebox
import sqlite3
import re

# Constants (written in caps)
REGULAR_FONT = ('Georgia', 14)
UNDERLINED_FONT = ('Georgia', 14, 'underline')
SMALL_FONT = ('Georgia', 12)
WINDOW_WIDTH, WINDOW_HEIGHT = 600, 600

# Set numbers as global variables
numbers = set('0123456789')

# Database to save user data
# create a / connect to Database
con = sqlite3.connect('User_Data.db')

# create Cursor
cur = con.cursor()

# create table
cur.execute('''CREATE TABLE IF NOT EXISTS User_Data (
            name text, 
            username text, 
            gender text, 
            password varchar,
            question text,
            answer text
            )''')

# commit changes to Database
con.commit()

# close connection
con.close()


class MainDisplay(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)

        # fill space allocated and expand if needed
        container.pack(side='top', fill='both', expand=True)

        # set minimum to 0 and priority in container
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # create dictionary
        self.frames = {}

        # puts frames (pages) into dictionary
        for F in (LoginPage, RegistrationForm, ChangePasswordForm):
            # put in container
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')

        # display login page
        self.show(LoginPage)

    # create function which shows the chosen frame (page)
    def show(self, controller):
        frame = self.frames[controller]
        frame.tkraise()


class LoginPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        login = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Login Questions (Username & Password)
        tk.Label(login, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=0, column=0, sticky='w',
                                                                                       padx=10)
        tk.Label(login, text='Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=2, column=0, sticky='w',
                                                                                       padx=10)

        # Login Answers (User entry)
        login_username = tk.Entry(login, font=REGULAR_FONT)
        login_password = tk.Entry(login, font=REGULAR_FONT)
        login_username.grid(row=1, column=0, padx=10)
        login_password.grid(row=3, column=0, padx=10)

        # Register Button & Forget Password Button (Redirect)
        register_button = tk.Button(login, width=15, text='Register?', font=UNDERLINED_FONT, relief='flat',
                                    command=lambda: controller.show(RegistrationForm))
        register_button.grid(row=4, column=0, sticky='w', padx=10)
        forgetpassword_button = tk.Button(login, width=15, text='Forget password?', font=UNDERLINED_FONT, relief='flat',
                                          command=lambda: controller.show(ChangePasswordForm))
        forgetpassword_button.grid(row=5, column=0, sticky='w', padx=10)

        # create function which verifies login
        def verify_login():
            log_user = login_username.get()
            log_password = login_password.get()

            # counts which fields have been filled
            counter = 0
            error = ''
            if log_user == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if log_password == '':
                error = 'All details must be filled up.'
            else:
                counter += 1

            # verify login using counter (check if all fields have been filled)
            if counter == 2:
                try:
                    # create / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()
                    # check whether data entered by user matches data in database
                    cur.execute('SELECT * from User_Data WHERE username = ? AND password = ?', (log_user, log_password))
                    if cur.fetchall():
                        # clear entry fields
                        login_username.delete(0, 'end')
                        login_password.delete(0, 'end')

                        # display successful login message
                        messagebox.showinfo(message='Login was successful.')
                    else:
                        messagebox.showerror(
                            message='Invalid username or password. Please check whether details have been '
                                    'entered correctly and that the account has been registered.')

                    # commit changes to Database
                    con.commit()
                    # close connection
                    con.close()

                except Exception as ep:
                    messagebox.showerror('', ep)
            else:
                messagebox.showerror('Error', error)

        # Login Button
        login_button = tk.Button(login, width=15, text='Login', font=REGULAR_FONT, relief='raised',
                                 command=verify_login)
        login_button.grid(row=4, column=1, sticky='e', padx=20, pady=10)

        login.place(anchor='center', relx=.5, rely=.5)


class RegistrationForm(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        register = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Registration Questions (Name, Username, Gender, Password, Password Confirmation, Security Question and Answer)
        tk.Label(register, text='Name', background='#FFFFFF', font=REGULAR_FONT).grid(row=0, column=0, sticky='w',
                                                                                      pady=10)
        tk.Label(register, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=1, column=0, sticky='w',
                                                                                          pady=10)
        tk.Label(register, text='Gender', background='#FFFFFF', font=REGULAR_FONT).grid(row=2, column=0, sticky='w',
                                                                                        pady=10)
        tk.Label(register, text='Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=3, column=0, sticky='w',
                                                                                          pady=10)
        tk.Label(register, text='Confirm Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=4, column=0,
                                                                                                  sticky='w', pady=10)
        tk.Label(register, text='Security Question', background='#FFFFFF', font=REGULAR_FONT).grid(row=5, column=0,
                                                                                                   sticky='w', pady=10)
        tk.Label(register, text='Security Answer', background='#FFFFFF', font=REGULAR_FONT).grid(row=6, column=0,
                                                                                                 sticky='w', pady=10)

        # Registration Answers (User Entry)
        # user only manually enters Name, Username, Password, Password Confirmation, Security Answer
        register_name = tk.Entry(register, font=REGULAR_FONT)
        register_username = tk.Entry(register, font=REGULAR_FONT)
        register_password = tk.Entry(register, font=REGULAR_FONT)
        confirm_password = tk.Entry(register, font=REGULAR_FONT)
        security_answer = tk.Entry(register, font=REGULAR_FONT)
        register_name.grid(row=0, column=1, pady=10, padx=20)
        register_username.grid(row=1, column=1, pady=10, padx=20)
        register_password.grid(row=3, column=1, pady=10, padx=20)
        confirm_password.grid(row=4, column=1, pady=10, padx=20)
        security_answer.grid(row=6, column=1, pady=10, padx=20)

        # create function which writes password criteria in entry box
        def show_criteria1(t):
            register_password.delete(0, 'end')

        register_password.insert(0, 'At least 1 number from 0 to 9.')
        register_password.bind('<FocusIn>', show_criteria1)
        register_password.config(width=20, font=REGULAR_FONT)

        def show_criteria2(t):
            confirm_password.delete(0, 'end')

        confirm_password.insert(0, 'At least 1 number from 0 to 9.')
        confirm_password.bind('<FocusIn>', show_criteria2)
        confirm_password.config(width=20, font=REGULAR_FONT)

        # user chooses Gender
        # define variable for Gender Options
        var = tk.StringVar()
        var.set('Male')

        # buttons for Gender Options
        register_gender = tk.LabelFrame(register, font=REGULAR_FONT)
        answer_male = tk.Radiobutton(register_gender, text='Male', background='#FFFFFF', variable=var,
                                     value='Male', font=SMALL_FONT)
        answer_female = tk.Radiobutton(register_gender, text='Female', background='#FFFFFF', variable=var,
                                       value='Female', font=SMALL_FONT)
        answer_other = tk.Radiobutton(register_gender, text='Other', background='#FFFFFF', variable=var,
                                      value='Other', font=SMALL_FONT)
        register_gender.grid(row=2, column=1, pady=10, padx=20)
        answer_male.pack(expand=True, side='left')
        answer_female.pack(expand=True, side='left')
        answer_other.pack(expand=True, side='left')

        # user chooses Security Questions
        # list for Security Questions
        questions = []
        # define variable for Security Questions
        variable = tk.StringVar()
        # text file of Security Questions
        world = open('securityquestions.txt', 'r')
        for securityquestions in world:
            securityquestions = securityquestions.rstrip('\n')
            # add Security Questions to list
            questions.append(securityquestions)
        variable.set(questions[5])

        # dropdown menu for Security Questions
        security_question = tk.OptionMenu(register, variable, *questions)
        security_question.grid(row=5, column=1)
        security_question.config(width=20, font=SMALL_FONT)

        # create function to verify registration
        def verify_register():
            # counts which fields have been filled
            counter = 0
            error = ''
            if register_name.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if register_username.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if var.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if register_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if confirm_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', register_password.get()) is None:
                error = 'Password must have at least 1 number.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', confirm_password.get()) is None:
                error = 'Password must have at least 1 number.'
            else:
                counter += 1
            # check whether passwords match
            if register_password.get() != confirm_password.get():
                error = 'Passwords do not match.'
            else:
                counter += 1
            if variable.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if security_answer.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1

            # verify register using counter (check if all fields have been filled, passwords fulfill criteria and match)
            if counter == 10:
                try:
                    # create a / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()

                    # enter into table
                    cur.execute('''INSERT INTO User_Data VALUES (:name, :username, :gender, 
                                                        :password, :question, :answer)''',
                                {
                                    'name': register_name.get(),
                                    'username': register_username.get(),
                                    'gender': var.get(),
                                    'password': register_password.get(),
                                    'question': variable.get(),
                                    'answer': security_answer.get()
                                })

                    # commit changes to Database
                    con.commit()
                    # close connection
                    con.close()

                    # clear entry fields
                    register_name.delete(0, 'end')
                    register_username.delete(0, 'end')
                    register_password.delete(0, 'end')
                    confirm_password.delete(0, 'end')
                    security_answer.delete(0, 'end')

                    # display successful registration message
                    messagebox.showinfo(message='Registration was successful.')

                    # redirect to Login Page
                    controller.show(LoginPage)

                except Exception as e:
                    messagebox.showerror('', e)
            else:
                messagebox.showerror('Error', error)

        # Register Button
        register_button = tk.Button(register, width=10, text='Register', font=REGULAR_FONT, relief='raised',
                                    command=verify_register)
        register_button.grid(row=7, column=1, sticky='e', pady=10, padx=20)
        register.place(anchor='center', relx=.5, rely=.5)


class ChangePasswordForm(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        password_change = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Change Password Form Questions (Username, Security Question, Security Answer, New Password and New Password
        # Confirmation)
        tk.Label(password_change, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=0,
                                                                                                 column=0, sticky='w',
                                                                                                 pady=10)
        tk.Label(password_change, text='User ID', background='#FFFFFF', font=REGULAR_FONT).grid(row=2,
                                                                                                column=0,
                                                                                                sticky='w',
                                                                                                pady=10)
        tk.Label(password_change, text='Security Question', background='#FFFFFF', font=REGULAR_FONT).grid(row=3,
                                                                                                          column=0,
                                                                                                          sticky='w',
                                                                                                          pady=10)
        tk.Label(password_change, text='Security Answer', background='#FFFFFF', font=REGULAR_FONT).grid(row=4,
                                                                                                        column=0,
                                                                                                        sticky='w',
                                                                                                        pady=10)
        tk.Label(password_change, text='New Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=5,
                                                                                                     column=0,
                                                                                                     sticky='w',
                                                                                                     pady=10)
        tk.Label(password_change, text='Confirm New Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=6,
                                                                                                             column=0,
                                                                                                             sticky='w',
                                                                                                             pady=10)

        # Change Password Form Answer (User Entry)
        # user only manually enters Username, Security Answer, New Password and New Password Confirmation
        check_username = tk.Entry(password_change, font=REGULAR_FONT)
        user_id = tk.Entry(password_change, font=REGULAR_FONT)
        check_securityanswer = tk.Entry(password_change, font=REGULAR_FONT)
        new_password = tk.Entry(password_change, font=REGULAR_FONT)
        confirm_newpassword = tk.Entry(password_change, font=REGULAR_FONT)
        check_username.grid(row=0, column=1, pady=10, padx=20)
        user_id.grid(row=2, column=1, pady=10, padx=20)
        check_securityanswer.grid(row=4, column=1, pady=10, padx=20)
        new_password.grid(row=5, column=1, pady=10, padx=20)
        confirm_newpassword.grid(row=6, column=1, pady=10, padx=20)

        # create function which finds User ID (oid)
        def query():
            # create / connect to Database
            con = sqlite3.connect('User_Data.db')
            # create Cursor
            cur = con.cursor()

            # Query Database
            # print primary key (oid) created by sqlite
            username_input = check_username.get()
            cur.execute('SELECT *, oid FROM User_Data WHERE username = ?', (username_input,))
            user_records = cur.fetchall()

            # define variables for print records and find security question
            print_records = ''
            find_securityquestion = ''

            # loop through results
            for user_record in user_records:
                print_records += str(user_record[0]) + '\t' + str(user_record[1]) + '\t' + str(user_record[6]) + '\n'
                find_securityquestion += str(user_record[4])

            # display User ID
            tk.Label(password_change, text=print_records, font=REGULAR_FONT).grid(row=1, column=1, padx=10, pady=10)
            tk.Label(password_change, text=find_securityquestion, font=REGULAR_FONT).grid(row=3, column=1,
                                                                                          padx=10, pady=10)

            # commit changes to Database
            con.commit()
            # close connection
            con.close()

        # Find User ID Button
        find_userid = tk.Button(password_change, width=10, text='Find User ID', font=REGULAR_FONT, relief='raised',
                                command=query)
        find_userid.grid(row=1, column=0, sticky='w', pady=10)

        # define function which writes password criteria in entry box
        def show_criteria1(t):
            new_password.delete(0, 'end')

        new_password.insert(0, 'At least 1 number from 0 to 9.')
        new_password.bind('<FocusIn>', show_criteria1)
        new_password.config(width=20, font=SMALL_FONT)

        def show_criteria2(t):
            confirm_newpassword.delete(0, 'end')

        confirm_newpassword.insert(0, 'At least 1 number from 0 to 9.')
        confirm_newpassword.bind('<FocusIn>', show_criteria2)
        confirm_newpassword.config(width=20, font=SMALL_FONT)

        # create function which updates password record
        def change_password():
            # define variable for User ID entered by user
            userid_input = user_id.get()
            # counts which fields have been filled, whether passwords fulfill criteria and match
            counter = 0
            error = ''
            if check_username.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if user_id.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if re.search('[0-9]', user_id.get()) is None:
                error = 'Please enter the correct User ID.'
            else:
                counter += 1
            if check_securityanswer.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if new_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if confirm_newpassword.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', new_password.get()) is None:
                error = 'Passwords must have at least 1 number.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', confirm_newpassword.get()) is None:
                error = 'Passwords must have at least 1 number.'
            else:
                counter += 1
            # check whether passwords match
            if new_password.get() != confirm_newpassword.get():
                error = 'Passwords do not match.'
            else:
                counter += 1

            # verify password change using counter (check if all fields have been filled, user id is correct,
            # passwords fulfill criteria and match)
            if counter == 9:
                try:
                    # create / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()

                    # Query Database
                    # check whether data entered by user matches data in database using User ID input (oid)
                    cur.execute('SELECT * FROM User_Data WHERE answer = ? AND oid = ?', (check_securityanswer.get(),
                                                                                         userid_input))
                    if cur.fetchall():
                        cur.execute('''UPDATE User_Data SET password = :password WHERE oid = :oid''',
                                    {'password': new_password.get(), 'oid': userid_input})

                        # commit changes to Database
                        con.commit()
                        # close connection
                        con.close()

                        # clear entry fields
                        check_username.delete(0, 'end')
                        user_id.delete(0, 'end')
                        check_securityanswer.delete(0, 'end')
                        new_password.delete(0, 'end')
                        confirm_newpassword.delete(0, 'end')

                        # message displayed saying password change was successful
                        messagebox.showinfo(message='Password was changed successfully..')

                        # redirect to Login Page
                        controller.show(LoginPage)

                    # display security answer is incorrect message
                    else:
                        messagebox.showerror(message='Security Answer is incorrect.')
                except Exception as e:
                    messagebox.showerror('', e)

            else:
                messagebox.showerror('Error', error)

        # Change Password Button
        changepassword_button = tk.Button(password_change, width=15, text='Change Password', font=REGULAR_FONT,
                                          relief='raised', command=change_password)
        changepassword_button.grid(row=7, column=1, sticky='e', padx=10, pady=10)

        password_change.place(anchor='center', relx=.5, rely=.5)


window = MainDisplay()
window.title('Maze Game')
window.config(background='#E1D4E7')

# Display window at the center of the screen
screen_width = window.winfo_width()
screen_height = window.winfo_height()

window_x = (screen_width / 2) - (WINDOW_WIDTH / 2)
window_y = (screen_height / 2) - (WINDOW_HEIGHT / 2)
window.geometry(f'{WINDOW_WIDTH}x{WINDOW_HEIGHT}+{int(window_x)}+{int(window_y)}')

window.mainloop()

'''

This is my code for a login page with registration form and change password form using tkinter on python. I am unable to center the main display window on my computer screen. This is at the bottom of my code. I am not sure how to fix this. The button formats (e.g. relief styles) also do not work. If there are any issues or suggestions in regards to my code, please do let me know as it would be greatly appreciated!

Edit: Background colour is now shown on display.

'''

import tkinter as tk
from tkinter import messagebox
import sqlite3
import re

# Constants (written in caps)
REGULAR_FONT = ('Georgia', 14)
UNDERLINED_FONT = ('Georgia', 14, 'underline')
SMALL_FONT = ('Georgia', 12)
WINDOW_WIDTH, WINDOW_HEIGHT = 600, 600

# Set numbers as global variables
numbers = set('0123456789')

# Database to save user data
# create a / connect to Database
con = sqlite3.connect('User_Data.db')

# create Cursor
cur = con.cursor()

# create table
cur.execute('''CREATE TABLE IF NOT EXISTS User_Data (
            name text, 
            username text, 
            gender text, 
            password varchar,
            question text,
            answer text
            )''')

# commit changes to Database
con.commit()

# close connection
con.close()


class MainDisplay(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)

        # fill space allocated and expand if needed
        container.pack(side='top', fill='both', expand=True)

        # set minimum to 0 and priority in container
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # create dictionary
        self.frames = {}

        # puts frames (pages) into dictionary
        for F in (LoginPage, RegistrationForm, ChangePasswordForm):
            # put in container
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')

        # display login page
        self.show(LoginPage)

    # create function which shows the chosen frame (page)
    def show(self, controller):
        frame = self.frames[controller]
        frame.tkraise()


class LoginPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        login = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Login Questions (Username & Password)
        tk.Label(login, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=0, column=0, sticky='w',
                                                                                       padx=10)
        tk.Label(login, text='Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=2, column=0, sticky='w',
                                                                                       padx=10)

        # Login Answers (User entry)
        login_username = tk.Entry(login, font=REGULAR_FONT)
        login_password = tk.Entry(login, font=REGULAR_FONT)
        login_username.grid(row=1, column=0, padx=10)
        login_password.grid(row=3, column=0, padx=10)

        # Register Button & Forget Password Button (Redirect)
        register_button = tk.Button(login, width=15, text='Register?', font=UNDERLINED_FONT, relief='flat',
                                    command=lambda: controller.show(RegistrationForm))
        register_button.grid(row=4, column=0, sticky='w', padx=10)
        forgetpassword_button = tk.Button(login, width=15, text='Forget password?', font=UNDERLINED_FONT, relief='flat',
                                          command=lambda: controller.show(ChangePasswordForm))
        forgetpassword_button.grid(row=5, column=0, sticky='w', padx=10)

        # create function which verifies login
        def verify_login():
            log_user = login_username.get()
            log_password = login_password.get()

            # counts which fields have been filled
            counter = 0
            error = ''
            if log_user == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if log_password == '':
                error = 'All details must be filled up.'
            else:
                counter += 1

            # verify login using counter (check if all fields have been filled)
            if counter == 2:
                try:
                    # create / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()
                    # check whether data entered by user matches data in database
                    cur.execute('SELECT * from User_Data WHERE username = ? AND password = ?', (log_user, log_password))
                    if cur.fetchall():
                        # clear entry fields
                        login_username.delete(0, 'end')
                        login_password.delete(0, 'end')

                        # display successful login message
                        messagebox.showinfo(message='Login was successful.')
                    else:
                        messagebox.showerror(
                            message='Invalid username or password. Please check whether details have been '
                                    'entered correctly and that the account has been registered.')

                    # commit changes to Database
                    con.commit()
                    # close connection
                    con.close()

                except Exception as ep:
                    messagebox.showerror('', ep)
            else:
                messagebox.showerror('Error', error)

        # Login Button
        login_button = tk.Button(login, width=15, text='Login', font=REGULAR_FONT, relief='raised',
                                 command=verify_login)
        login_button.grid(row=4, column=1, sticky='e', padx=20, pady=10)

        login.place(anchor='center', relx=.5, rely=.5)


class RegistrationForm(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        register = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Registration Questions (Name, Username, Gender, Password, Password Confirmation, Security Question and Answer)
        tk.Label(register, text='Name', background='#FFFFFF', font=REGULAR_FONT).grid(row=0, column=0, sticky='w',
                                                                                      pady=10)
        tk.Label(register, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=1, column=0, sticky='w',
                                                                                          pady=10)
        tk.Label(register, text='Gender', background='#FFFFFF', font=REGULAR_FONT).grid(row=2, column=0, sticky='w',
                                                                                        pady=10)
        tk.Label(register, text='Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=3, column=0, sticky='w',
                                                                                          pady=10)
        tk.Label(register, text='Confirm Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=4, column=0,
                                                                                                  sticky='w', pady=10)
        tk.Label(register, text='Security Question', background='#FFFFFF', font=REGULAR_FONT).grid(row=5, column=0,
                                                                                                   sticky='w', pady=10)
        tk.Label(register, text='Security Answer', background='#FFFFFF', font=REGULAR_FONT).grid(row=6, column=0,
                                                                                                 sticky='w', pady=10)

        # Registration Answers (User Entry)
        # user only manually enters Name, Username, Password, Password Confirmation, Security Answer
        register_name = tk.Entry(register, font=REGULAR_FONT)
        register_username = tk.Entry(register, font=REGULAR_FONT)
        register_password = tk.Entry(register, font=REGULAR_FONT)
        confirm_password = tk.Entry(register, font=REGULAR_FONT)
        security_answer = tk.Entry(register, font=REGULAR_FONT)
        register_name.grid(row=0, column=1, pady=10, padx=20)
        register_username.grid(row=1, column=1, pady=10, padx=20)
        register_password.grid(row=3, column=1, pady=10, padx=20)
        confirm_password.grid(row=4, column=1, pady=10, padx=20)
        security_answer.grid(row=6, column=1, pady=10, padx=20)

        # create function which writes password criteria in entry box
        def show_criteria1(t):
            register_password.delete(0, 'end')

        register_password.insert(0, 'At least 1 number from 0 to 9.')
        register_password.bind('<FocusIn>', show_criteria1)
        register_password.config(width=20, font=REGULAR_FONT)

        def show_criteria2(t):
            confirm_password.delete(0, 'end')

        confirm_password.insert(0, 'At least 1 number from 0 to 9.')
        confirm_password.bind('<FocusIn>', show_criteria2)
        confirm_password.config(width=20, font=REGULAR_FONT)

        # user chooses Gender
        # define variable for Gender Options
        var = tk.StringVar()
        var.set('Male')

        # buttons for Gender Options
        register_gender = tk.LabelFrame(register, font=REGULAR_FONT)
        answer_male = tk.Radiobutton(register_gender, text='Male', background='#FFFFFF', variable=var,
                                     value='Male', font=SMALL_FONT)
        answer_female = tk.Radiobutton(register_gender, text='Female', background='#FFFFFF', variable=var,
                                       value='Female', font=SMALL_FONT)
        answer_other = tk.Radiobutton(register_gender, text='Other', background='#FFFFFF', variable=var,
                                      value='Other', font=SMALL_FONT)
        register_gender.grid(row=2, column=1, pady=10, padx=20)
        answer_male.pack(expand=True, side='left')
        answer_female.pack(expand=True, side='left')
        answer_other.pack(expand=True, side='left')

        # user chooses Security Questions
        # list for Security Questions
        questions = []
        # define variable for Security Questions
        variable = tk.StringVar()
        # text file of Security Questions
        world = open('securityquestions.txt', 'r')
        for securityquestions in world:
            securityquestions = securityquestions.rstrip('\n')
            # add Security Questions to list
            questions.append(securityquestions)
        variable.set(questions[5])

        # dropdown menu for Security Questions
        security_question = tk.OptionMenu(register, variable, *questions)
        security_question.grid(row=5, column=1)
        security_question.config(width=20, font=SMALL_FONT)

        # create function to verify registration
        def verify_register():
            # counts which fields have been filled
            counter = 0
            error = ''
            if register_name.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if register_username.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if var.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if register_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if confirm_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', register_password.get()) is None:
                error = 'Password must have at least 1 number.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', confirm_password.get()) is None:
                error = 'Password must have at least 1 number.'
            else:
                counter += 1
            # check whether passwords match
            if register_password.get() != confirm_password.get():
                error = 'Passwords do not match.'
            else:
                counter += 1
            if variable.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if security_answer.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1

            # verify register using counter (check if all fields have been filled, passwords fulfill criteria and match)
            if counter == 10:
                try:
                    # create a / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()

                    # enter into table
                    cur.execute('''INSERT INTO User_Data VALUES (:name, :username, :gender, 
                                                        :password, :question, :answer)''',
                                {
                                    'name': register_name.get(),
                                    'username': register_username.get(),
                                    'gender': var.get(),
                                    'password': register_password.get(),
                                    'question': variable.get(),
                                    'answer': security_answer.get()
                                })

                    # commit changes to Database
                    con.commit()
                    # close connection
                    con.close()

                    # clear entry fields
                    register_name.delete(0, 'end')
                    register_username.delete(0, 'end')
                    register_password.delete(0, 'end')
                    confirm_password.delete(0, 'end')
                    security_answer.delete(0, 'end')

                    # display successful registration message
                    messagebox.showinfo(message='Registration was successful.')

                    # redirect to Login Page
                    controller.show(LoginPage)

                except Exception as e:
                    messagebox.showerror('', e)
            else:
                messagebox.showerror('Error', error)

        # Register Button
        register_button = tk.Button(register, width=10, text='Register', font=REGULAR_FONT, relief='raised',
                                    command=verify_register)
        register_button.grid(row=7, column=1, sticky='e', pady=10, padx=20)
        register.place(anchor='center', relx=.5, rely=.5)


class ChangePasswordForm(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        password_change = tk.Frame(self, bd=1, background='#FFFFFF', relief='solid', padx=20, pady=20)

        # Change Password Form Questions (Username, Security Question, Security Answer, New Password and New Password
        # Confirmation)
        tk.Label(password_change, text='Username', background='#FFFFFF', font=REGULAR_FONT).grid(row=0,
                                                                                                 column=0, sticky='w',
                                                                                                 pady=10)
        tk.Label(password_change, text='User ID', background='#FFFFFF', font=REGULAR_FONT).grid(row=2,
                                                                                                column=0,
                                                                                                sticky='w',
                                                                                                pady=10)
        tk.Label(password_change, text='Security Question', background='#FFFFFF', font=REGULAR_FONT).grid(row=3,
                                                                                                          column=0,
                                                                                                          sticky='w',
                                                                                                          pady=10)
        tk.Label(password_change, text='Security Answer', background='#FFFFFF', font=REGULAR_FONT).grid(row=4,
                                                                                                        column=0,
                                                                                                        sticky='w',
                                                                                                        pady=10)
        tk.Label(password_change, text='New Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=5,
                                                                                                     column=0,
                                                                                                     sticky='w',
                                                                                                     pady=10)
        tk.Label(password_change, text='Confirm New Password', background='#FFFFFF', font=REGULAR_FONT).grid(row=6,
                                                                                                             column=0,
                                                                                                             sticky='w',
                                                                                                             pady=10)

        # Change Password Form Answer (User Entry)
        # user only manually enters Username, Security Answer, New Password and New Password Confirmation
        check_username = tk.Entry(password_change, font=REGULAR_FONT)
        user_id = tk.Entry(password_change, font=REGULAR_FONT)
        check_securityanswer = tk.Entry(password_change, font=REGULAR_FONT)
        new_password = tk.Entry(password_change, font=REGULAR_FONT)
        confirm_newpassword = tk.Entry(password_change, font=REGULAR_FONT)
        check_username.grid(row=0, column=1, pady=10, padx=20)
        user_id.grid(row=2, column=1, pady=10, padx=20)
        check_securityanswer.grid(row=4, column=1, pady=10, padx=20)
        new_password.grid(row=5, column=1, pady=10, padx=20)
        confirm_newpassword.grid(row=6, column=1, pady=10, padx=20)

        # create function which finds User ID (oid)
        def query():
            # create / connect to Database
            con = sqlite3.connect('User_Data.db')
            # create Cursor
            cur = con.cursor()

            # Query Database
            # print primary key (oid) created by sqlite
            username_input = check_username.get()
            cur.execute('SELECT *, oid FROM User_Data WHERE username = ?', (username_input,))
            user_records = cur.fetchall()

            # define variables for print records and find security question
            print_records = ''
            find_securityquestion = ''

            # loop through results
            for user_record in user_records:
                print_records += str(user_record[0]) + '\t' + str(user_record[1]) + '\t' + str(user_record[6]) + '\n'
                find_securityquestion += str(user_record[4])

            # display User ID
            tk.Label(password_change, text=print_records, font=REGULAR_FONT).grid(row=1, column=1, padx=10, pady=10)
            tk.Label(password_change, text=find_securityquestion, font=REGULAR_FONT).grid(row=3, column=1,
                                                                                          padx=10, pady=10)

            # commit changes to Database
            con.commit()
            # close connection
            con.close()

        # Find User ID Button
        find_userid = tk.Button(password_change, width=10, text='Find User ID', font=REGULAR_FONT, relief='raised',
                                command=query)
        find_userid.grid(row=1, column=0, sticky='w', pady=10)

        # define function which writes password criteria in entry box
        def show_criteria1(t):
            new_password.delete(0, 'end')

        new_password.insert(0, 'At least 1 number from 0 to 9.')
        new_password.bind('<FocusIn>', show_criteria1)
        new_password.config(width=20, font=SMALL_FONT)

        def show_criteria2(t):
            confirm_newpassword.delete(0, 'end')

        confirm_newpassword.insert(0, 'At least 1 number from 0 to 9.')
        confirm_newpassword.bind('<FocusIn>', show_criteria2)
        confirm_newpassword.config(width=20, font=SMALL_FONT)

        # create function which updates password record
        def change_password():
            # define variable for User ID entered by user
            userid_input = user_id.get()
            # counts which fields have been filled, whether passwords fulfill criteria and match
            counter = 0
            error = ''
            if check_username.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if user_id.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if re.search('[0-9]', user_id.get()) is None:
                error = 'Please enter the correct User ID.'
            else:
                counter += 1
            if check_securityanswer.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if new_password.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            if confirm_newpassword.get() == '':
                error = 'All details must be filled up.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', new_password.get()) is None:
                error = 'Passwords must have at least 1 number.'
            else:
                counter += 1
            # check whether password fulfills the criteria
            if re.search('[0-9]', confirm_newpassword.get()) is None:
                error = 'Passwords must have at least 1 number.'
            else:
                counter += 1
            # check whether passwords match
            if new_password.get() != confirm_newpassword.get():
                error = 'Passwords do not match.'
            else:
                counter += 1

            # verify password change using counter (check if all fields have been filled, user id is correct,
            # passwords fulfill criteria and match)
            if counter == 9:
                try:
                    # create / connect to Database
                    con = sqlite3.connect('User_Data.db')
                    # create Cursor
                    cur = con.cursor()

                    # Query Database
                    # check whether data entered by user matches data in database using User ID input (oid)
                    cur.execute('SELECT * FROM User_Data WHERE answer = ? AND oid = ?', (check_securityanswer.get(),
                                                                                         userid_input))
                    if cur.fetchall():
                        cur.execute('''UPDATE User_Data SET password = :password WHERE oid = :oid''',
                                    {'password': new_password.get(), 'oid': userid_input})

                        # commit changes to Database
                        con.commit()
                        # close connection
                        con.close()

                        # clear entry fields
                        check_username.delete(0, 'end')
                        user_id.delete(0, 'end')
                        check_securityanswer.delete(0, 'end')
                        new_password.delete(0, 'end')
                        confirm_newpassword.delete(0, 'end')

                        # message displayed saying password change was successful
                        messagebox.showinfo(message='Password was changed successfully..')

                        # redirect to Login Page
                        controller.show(LoginPage)

                    # display security answer is incorrect message
                    else:
                        messagebox.showerror(message='Security Answer is incorrect.')
                except Exception as e:
                    messagebox.showerror('', e)

            else:
                messagebox.showerror('Error', error)

        # Change Password Button
        changepassword_button = tk.Button(password_change, width=15, text='Change Password', font=REGULAR_FONT,
                                          relief='raised', command=change_password)
        changepassword_button.grid(row=7, column=1, sticky='e', padx=10, pady=10)

        password_change.place(anchor='center', relx=.5, rely=.5)


window = MainDisplay()
window.title('Maze Game')
window.config(background='#E1D4E7')

# Display window at the center of the screen
screen_width = window.winfo_width()
screen_height = window.winfo_height()

window_x = (screen_width / 2) - (WINDOW_WIDTH / 2)
window_y = (screen_height / 2) - (WINDOW_HEIGHT / 2)
window.geometry(f'{WINDOW_WIDTH}x{WINDOW_HEIGHT}+{int(window_x)}+{int(window_y)}')

window.mainloop()

'''

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤芳又自赏 2025-01-17 07:57:05

您可以使用 window.eval("tk::PlaceWindow .center") 使窗口出现在屏幕中央。
颜色代码“#E1D4E7”似乎更接近白色,尝试使用任何其他较暗的颜色来验证它是否有效

You can use window.eval("tk::PlaceWindow . center") to make the window appear in the center of the screen.
The color code "#E1D4E7" appears to be closer to white, try using any other darker colors to verify if it works

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文