Login and password python

Пишем форму авторизации на Python Tkinter

В данной статье мы рассмотрим с Вами как можно быстро создать графическое приложение с использованием библиотеки Python Tkinter. Проектировать мы будем экран авторизации, в который пользователь должен ввести свой логин и пароль. Версия Python, которая используется в коде 3.8. Код с комментариями представлен ниже.

# импортируем библиотеку tkinter всю сразу
from tkinter import *
from tkinter import messagebox

# главное окно приложения
window = Tk()
# заголовок окна
window.title(‘Авторизация’)
# размер окна
window.geometry(‘450×230’)
# можно ли изменять размер окна — нет
window.resizable(False, False)

# кортежи и словари, содержащие настройки шрифтов и отступов
font_header = (‘Arial’, 15)
font_entry = (‘Arial’, 12)
label_font = (‘Arial’, 11)
base_padding =
header_padding =

# обработчик нажатия на клавишу ‘Войти’
def clicked():

# получаем имя пользователя и пароль
username = username_entry.get()
password = password_entry.get()

# выводим в диалоговое окно введенные пользователем данные
messagebox.showinfo(‘Заголовок’, ‘, ‘.format(username=username, password=password))

# заголовок формы: настроены шрифт (font), отцентрирован (justify), добавлены отступы для заголовка
# для всех остальных виджетов настройки делаются также
main_label = Label(window, text=’Авторизация’, font=font_header, justify=CENTER, **header_padding)
# помещаем виджет в окно по принципу один виджет под другим
main_label.pack()

# метка для поля ввода имени
username_label = Label(window, text=’Имя пользователя’, font=label_font , **base_padding)
username_label.pack()

# поле ввода имени
username_entry = Entry(window, bg=’#fff’, fg=’#444′, font=font_entry)
username_entry.pack()

# метка для поля ввода пароля
password_label = Label(window, text=’Пароль’, font=label_font , **base_padding)
password_label.pack()

# поле ввода пароля
password_entry = Entry(window, bg=’#fff’, fg=’#444′, font=font_entry)
password_entry.pack()

# кнопка отправки формы
send_btn = Button(window, text=’Войти’, command=clicked)
send_btn.pack(**base_padding)

# запускаем главный цикл окна
window.mainloop()

Теперь проясню пару моментов в коде:

1) в коде используется вот такая конструкция **header_padding — это операция разложения словаря в составляющие переменные. В нашем примере преобразование будет выглядеть следующим образом: **header_padding = -> header_padding -> padx=10, pady=12. Т.е. в конструктор класса Label, например, фактически будут передаваться правильные параметры. Это сделано для удобства, чтобы несколько раз не писать одни и теже настройки отступов. 2) у виджетов (Label, Button, Entry) — есть несколько менеджеров расположения, которые определяют, как дочерний виджет будет располагаться в родительском окне (контейнере). В примере, был использован метод pack(), который, по умолчанию, располагает виджет один под другим.

Таким образом, мы создали кроссплатформенное графическое приложение на Python — авторизация пользователя, которое может пригодиться на практике, остается добавить логику авторизации в методе clicked.

А для тех кто интересуется языком Python — я записал видеокурс Программированию на Python с Нуля до Гуру, в 5-ом разделе которого Создание программ с GUI подробно описывается все компоненты, необходимые для создания Python приложения c графическим интерфейсом.

Создано 23.02.2021 10:48:35

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    Basic Login and Registration System to be Used by New Developers to Structure their own Modules

    br34th3r/PythonLoginAndRegister

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    Python Login And Register

    Basic Login and Registration System to be Used by New Developers to Structure their own Modules

    Python Login and Register is a module developed to provide basic user authentication in Python. It is a very bare-bones structure for the reason that other developers can access the contents of the source files and look around in order to learn how to structure their own modules or projects. Furthermore, the module provides a quick access to check user validation through comparison with another Python variable or direct string value, and a developer can easily use the in-built functions to create a user registration system. Python Login and Register can only be used to regsiter users with the following information:

    Refer to the documentation section for specific information on what methods can be called to interact with Users and add information

    The creation of a user is quite simple and has two options, you can use either of the following methods :

    # Option 1 person = createUser("NAME", "SURNAME", "EMAIL", "PASSWORD) # Option 2 person = User("NAME", "SURNAME", "EMAIL", "PASSWORD")

    Furthermore, the module comes with an in-built entry form to create a user. This can be used in the command line and one can customise the input message for the input and so could be used by administrators to quickly create users. This is done with the following function :

    # Input New User with a Form person = inputUser("NAME ENTRY PROMPT", "SURNAME ENTRY PROMPT", "EMAIL ENTRY PROMPT", "PASSWORD ENTRY PROMPT")

    The User object now has some accessible properties. These are the name, surname, email and password properties. These can be called as variables to the object like so :

    # Call User Information person1.name person1.surname person1.email person1.password

    There are two options currently to list the current users. One ‘safe’ way and one ‘unsafe’ way. These are as follows :

    # List All Users Without Displaying Passwords (safe) listUsers() # List All Users While Displaying Passwords (unsafe) unsafeList()

    The unsafe listing of users will require an admin with access to the terminal to confirm the listing of the users in an ‘unsafe’ fashion

    A user can be checked to see if their object exists using the following function :

    # Check if a User Exists userExists("EMAIL", "PASSWORD")

    This function will return True or False respectively depending on the value. This is a search through the whole array for a specific user to see if they exist or not and could be used to validate logins, however a second check should be run to make sure this is not a form of bruteforcing

    A User can be validated at any point in the code quite easily to see if their password matches a prescribed standard password that the developer invokes.

    # Validate an Existing User validateUser(UserObject, "PASSWORD")

    Unlike User Eistance, User Validation uses a preset password and only requires the single user object to validate. This means that the system does not have to browse an entire array for a user to validate, when the user information is stored on a local object

    A user can simply be removed from an array by calling the following function with their email as the parameter :

    # Remove a Specific User removeUser("EMAIL")

    The following examples can be used to show basic functionality of the system

    email = str(input("Enter Your Email : ")) password = str(input("Enter Your Password : ")) if userExists(email, password): print("Welcome!") else: print("Sorry, Invalid Credentials!")

    Basic Registration (Without Registration Function)

    name = str(input("Enter Your Name : ")) surname = str(input("Enter Your Surname : ")) email = str(input("Enter Your Email : ")) password = str(input("Enter Your Password : ")) confPassword = str(input("Confirm Your Password : ")) if(password == confPassword): print("User Accepted!") user = createUser(name, surname, email, password) else: print("User Rejected! Invalid Password Combination")

    Conditionals can be used to create more validation methods, functions are planned to be implemented in the near future

    Basic Registration (With Registration Function)

    user = inputUser("Enter Your First Name : ", "Enter Your Surname : ", "Enter Your Email : ", "Enter Your Intended Password : ")
    user = createUser("Josh", "Jameson", "joshywashy1@spaceymail.com", "MIDAS") adminPassword = "MIDAS" if validateUser(user, adminPassword): print("You have Admin Access!") else: print("You Don't Have Admin Access!")

    Please don’t use this code, it’s very insecure and any user that sets their password as MIDAS will have admin access! Demonstration Purposes Only!

    Remove a User from the System

    user = createUser("Josh", "Jameson", "joshywashy1@spaceymail.com", "MIDAS") if validateUser(user, "ZEUS") != True: removeUser(user.email) else: print("Welcome!")

    Python setup.py installation :

    pip install PythonLoginAndRegister

    Источник

    Python GUI Login – Graphical Registration And Login System In Python

    Python GUI Login

    Welcome to Python GUI Login tutorial. In this tutorial i will teach you to create a Login form where user can register themselves and can login. Registration and Login requires everywhere, either you are filling any form or want to access any application. So in this tutorial we will see how to implement user registration and login in python.

    In this, we will create a GUI interface. Python provides Tkinter toolkit to develop GUI applications. In python, you can develop any GUI applications easily. If you have ideas then you can turn your imagination into reality and make many creative things in programming. So without wasting time let’s start our Python GUI Login tutorial. It may be lengthy so guys please keep patience and follow this till the end, and i am pretty sure you will learn much knowledge and also enjoy.

    Python GUI Login

    Python GUI Login Tutorial – Getting Started With Tkinter

    Creating New Project

    Open your IDE and create a new project and then inside this project create a python file. I prefer PyCharm but you can prefer anyone as it doesn’t matters, but if you want to know best python IDEs then refer Best Python IDEs.

    Importing Tkinter Module

    For importing tkinter just write one line of code.

    Источник

    Читайте также:  Верстка html css уроки
    Оцените статью