Как сделать окно регистрации в python

Обновлено: 13.05.2024

Kivy является независимой от платформы, так как он может работать на Android, IOS, Linux, Windows и т. Д. Kivy предоставляет вам функциональность, чтобы написать код один раз и запустить его на разных платформах. Он в основном используется для разработки приложения Android, но это не значит, что его нельзя использовать в приложениях для настольных компьютеров.

Используйте эту команду для установки kivy:

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

Чтобы сделать страницу входа в систему, нам сначала нужно импортировать некоторые функции kivy — widgets , gridlayout .

from kivy.app import App

from kivy.uix.gridlayout import GridLayout

from kivy.uix.label import Label

from kivy.uix.textinput import TextInput

def __init__( self , * * var_args):

super (LoginScreen, self ).__init__( * * var_args)

self .add_widget(Label(text = 'User Name' ))

self .add_widget(Label(text = 'password' ))

self .password = TextInput(password = True , multiline = False )

self .add_widget(Label(text = 'Comfirm password' ))

self .password = TextInput(password = True , multiline = False )

self .add_widget( self .password)

if __name__ = = '__main__' :


Выход:

Объяснение кода:

class LoginScreen(GridLayout) :

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

В class LoginScreen мы переопределяем метод __init__() чтобы добавлять виджеты и определять их поведение.

def __init__( self , * * kwargs):

super (LoginScreen, self ).__init__( * * kwargs)

Не следует забывать вызывать super для реализации функциональности исходного класса.
перегружен. Также обратите внимание, что хорошей практикой является не пропускать **kwargs при вызове super, так как они иногда используются внутри.

self .add_widget(Label(text = 'User Name' ))

self .add_widget(Label(text = 'password' ))

self .password = TextInput(password = True , multiline = False )

self .add_widget( self .password)

class MyApp :

Здесь метод build() «Инициализирует приложение; он будет вызван только один раз. Если этот метод возвращает виджет (дерево), он будет использован как корневой виджет и добавлен в окно.
Возвращает: None или корневой экземпляр Widget, если self.root не существует ».

Самое приятное то, что попробуйте изменить размер окна, и вы увидите, что виджеты на экране корректируются в соответствии с размером окна, потому что виджеты по умолчанию используют подсказки размера.


Например :

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

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

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

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 графическим интерфейсом.


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

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

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

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

Она выглядит вот так:

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

This complete python tutorial explains, how to create a Registration form using Python Tkinter and a login page in python Tkinter with database sqlite3. Also, I have explained how to validate form fields in the registration form in Python Tkinter. I hope, you will like this, registration form in Python using Tkinter example.

All the data will be stored and fetched using the SQLite3 database. This is a complete project on the registration form in python with database, that can be used to add registration & login screens to any desktop application in Python.

Login and Registration form in Python using Tkinter Overview

  • The Login and Registration forms are created using Python library ‘Tkinter.’ [Read more about Python Tkinter]
  • Tkinter allows creating GUI-based applications and is rich with helpful widgets.
  • For the database, we have used SQLite3 which comes pre-installed with python. It is a lighter version of SQL and can hold 281 terabytes of data.
  • We have added validation on all the Entry Fields in the project that means it is mandatory to provide all the information. Not doing so will prompt an error message.
  • Exception handlers are used to avoid breaking the program also you will see the error using a message box.
  • Names of all the countries in the ‘North America‘ continent are displayed in the dropdown. If you want to add more countries, simply replace countries.txtwith your text file but make sure to change the name in the code at line 129. An easier way would be to edit the data of inside countries.txt.
  • Here is the description of widgets used in the program. Also, we have a dedicated section for each widget used in the project and we added a link in front of each.

Python Tkinter Registration Form

In this section, we will talk about the registration form in python using tkinter. We will be discussing widgets and the purpose of using them at that point. The code shared here is only for the interface of the registration page. Complete application code is shared at the bottom of the page.

Frame Widget

  • ws is the main window on which we are going to place a frame
  • bd is the border of the frame
  • bg is the background colour.
  • relief is to provide a special effect.
  • Here geometry method used is ‘pack’ but in the full code below we have used the place as place allows us to position the widget with higher accuracy.
  • the thought behind creating this widget is to place other widgets inside it so that everything looks organized.

Label Widget

  • The Label is used to add text to the application. We have used Label multiple times to display different text.
  • Here I will be explaining it once and that will be applicable on all the labels used in the program.
  • in the below code Label is the keyword used to create the label widget.
  • We are placing this label on the right_frame.
  • any text added here will be displayed on the application
  • We are using grid as a geometry method to position the text.

Entry Widget

  • The Entry widget is used to take input from the user. It provides a blank space where the user can type any text.
  • Entry widget is used multiple times in the code this explanation is implemented on all.
  • Entry keyword is used to all call entry widget and it is placed on the right_frame
  • We are using the grid as a geometry method to position the text.

Radiobutton

  • The Radiobutton is used to provide multiple options to the user but the user can select only one option.
  • We have created another frame with the name ‘gender_frame’ to hold all the radio buttons.
  • text is the name we want to show next to Radiobutton like in this case ‘male’.
  • bg is the background color of the Radiobutton.
  • variable means the value will change so in this case we have set it var which is StringVar(). Now the value provided must be a string. If var is set to IntVar() in that case value should be an integer.
  • value could be an integer or string depends upon the type of variable we have used. Value helps in identifying which radio button is selected.
  • pack geometry method is used with permission to expand in available space & stick to their left.
  • When 3 radio buttons are placed with the same properties then they all look the same and organized.

OptionMenu

  • OptionMenu is used to create a dropdown in the application. It is not ideal to display large data because it does not have a scrollbar but it consumes less space and displays the appropriate amount of options.
  • We have used OptionMenu to display a list of countries of the North America Continent.
  • under step 1 we have used the keyword OptionMenu to create the widget and we have placed it inside the right_frame, variable assigned is StringVar() which means different string values will be involved. *countries mean all the countries on the list.
  • under step 2 we have countries = [] which is an empty list and it will be appended by country names. variable =StringVar() means string will keep on changing.
  • under step 3 we are reading the country names from a text file then using a loop we are appending each country inside the list. country.rstrip('\n') it removes \n from the list.
  • grid is the geometry method used to position the widget.

Button

  • The Button in Python Tkinter is used to trigger activity. Something should happen when it is clicked.
  • In this application, the button is used to save the data inside the database.
  • Button keyword is used to create a widget and it is placed inside the right_frame.
  • width is the right and the left space of the button
  • text is the name displayed on the button.
  • the cursor is the icon of the mouse pointer. We have used hand2 that means every time user will take the cursor on the button, the cursor will turn into a pointing finger.
  • command holds the information about what will happen if the button is clicked. Here we have set it to None which means nothing will happen but in the full code, we have provided a function name to it.

Registration form using tkinter code

Here is the complete code snippet for the registration form in python using tkinter. This program shares no dependency with the complete code only in terms of User Interface.

Output:

In this output, you can see that a registration form is created using Python Tkinter. The form has Entry and Selection Fields created using Python Tkinter widgets.

registration form using tkinter

Login page in Python Tkinter with database

This section will see a code explanation for the login page in python tkinter with database. The complete application code is shared at end of the page. The code shown in this section is complete in terms of user interface only.

Frame Widget in Python Tkinter

  • Frame widget allows placing other widgets on it. Application look organizes if other widgets are placed on the frame also it gives control over sections.
  • Here left_frame is used to create the login section of the application.
  • Frame keyword is used to call frame widget and it is placed on the main window i.e ws.
  • bd is the border width of the frame widget in Python Tkinter
  • relief has different modes by we have used SOLID, it draws the outline. around the frame.

Label Widget in Python Tkinter

  • The Label is used to add text to the application.
  • in the below code Label is the keyword used to create the label widget.
  • We are placing this label on the left_frame.
  • any text added here will be displayed on the application
  • We are using grid as a geometry method to position the text.

Entry Widget in Python Tkinter

  • The Entry widget is used to take input from the user. It provides a blank space where the user can type any text.
  • Entry keyword is used to all call entry widget and it is placed on the left_frame
  • We are using the grid as a geometry method to position the text.

Button Widget in Python Tkinter

  • The Button in Python Tkinter is used to trigger activity. Something should happen when it is clicked.
  • In this application, the button is used to save the data inside the database.
  • Button keyword is used to create a widget and it is placed inside the left_frame.
  • width is the right and the left space of the button
  • text is the name displayed on the button.
  • the cursor is the icon of the mouse pointer. We have used hand2 that means every time user will take the cursor on the button, the cursor will turn into a pointing finger.
  • command holds the information about what will happen if the button is clicked. Here we have set it to None which means nothing will happen but in the full code, we have provided a function name to it.

Complete Code Snippet for Login:

Here is the complete code snippet for the Login form using Python Tkinter. This program shares no dependency with the complete code only in terms of User Interface.

Output:

In this output, you can see that a login form is created using Python Tkinter.

simple login form in python

This is how the login page in python tkinter with database looks like.

Registration form using tkinter validation for empty fields

  • In this section, we will see the code for identifying the empty fields in the Python Tkinter Registration form, we will see how we can make this mandatory for the user to provide input in the respective text field or selection fields like Radiobutton and OptionMenu.
  • We have used a simple strategy to do so. We are checking each Entry field and every time the user has provided input we are incrementing the check_counter variable by 1.
  • We have the count of total Entry Fields now we are checking check_count with the total number of fields. If they are equal then the application will proceed and save the data otherwise it will throw an error message for the respective empty field.
  • Another validation used in the application is for passwords. Since we two fields for the password in the register form.
    • Enter Password
    • Renter Password

    Code Snippet:

    Here is the code used to validate the entry fields in registration form in python.

    Output:

    In this output, user is trying to register without providing contact number so he has received an error prompt with the mistake mentioned on it. The same thing will happen if user tries to skip any other field.

    registration form in python with database

    Code Snippet:

    Here is the code snippet for the password do not match validation.

    Output:

    Here is the output showing the error prompted when password didn’t matched.

    registration form in python using tkinter

    This is how we can implement validation in the registration form using tkinter.

    Save Python Tkinter registration form data to sqlite3

    As we know, this is an example of a registration form in python using Tkinter with database, in this application, we have used SQLite3 to store data in a database. SQLite3 comes preinstalled with python all you need to is import sqlite3 . to access the data inside the database you can use DB Browser.

    Create Database using SQLite in Python Tkinter

    This line of code will create a database with the name userdata.db. This file will be stored in the same location where the main file is stored. Using Db Browser you can view and edit the data.

    Use the below code you can create table for the database.

    Insert Data using SQLite in Python Tkinter

    Here is the output of the record and this is the interface of the Db Browser software.

    registration form in python using tkinter with database

    Full Code Snippet:

    Here is the full code of application created using Python Tkinter. We have explained the entire code above section wise.

    Output:

    In this output, you can see the interface of the main application. We have a login screen on the left and a signup screen on the right. It is mandatory to provide all the information in both the login and registration screens.

    registration form in python using tkinter with database

    In this screen, the user trying to log in is not registered that is why she is seeing this error message. The same error will appear if the registered user will put in the wrong credentials.

    login page in python tkinter with database

    This is the validation error, user tried to logged in without all fields filled.

    login page in python tkinter with database sqlite3

    This is another validation error, it is important that Password and re-entered passwords are same.

    login and registration form in python tkinter

    In this output user has provided all the information and password matched with re-enter password column. The user is registered with the application.

    login page in python tkinter with database

    In this output, you can see that already registered user can login by providing the correct credentials..

    python registration form code tkinter

    Below you can see, the registration form in python using tkinter data has been saved the sqlite3 database.

    registration form in python using tkinter with database

    You may also like:

    I hope you must have been enjoyed the complete login and registration form in python Tkinter example, try the code on your own. It solved the below queries:

    • registration form in python with database
    • registration form in python using tkinter with database
    • registration form in python using tkinter
    • python registration form code tkinter
    • login page in python tkinter with database sqlite3
    • simple login form in python

    Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

    К данному моменту мы создали блог на Django, который использует формы для создания, редактирования и удаления статей, однако главный элемент большинства веб-сайтов все еще отсутствует: аутентификация пользователя.

    Содержание статьи

    Есть вопросы по Python?

    На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

    Telegram Чат & Канал

    Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

    Паблик VK

    Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

    При создании любого нового проекта, Django по умолчанию устанавливает приложение auth . В нем есть объект User, содержащий такие поля как:

    • username;
    • password;
    • email;
    • first_name;
    • last_name.

    Мы используем объект User для реализации входа, выхода и регистрации пользователя в блоге на Django.

    Аутентификация пользователя в Django (LoginView)

    По умолчанию, Django поставляется с представлением LoginView для страницы входа. Нам нужно только настроить:

    • URL маршруты для системы аутентификации;
    • создать HTML шаблон для страницы входа;
    • обновить файл settings.py .

    Для начала обновим файл blog_project/urls.py . Поместим страницы для входа и для выхода на URL префиксе accounts . Небольшое добавление на предпоследней строке.

    Как отмечается в документации к LoginView, по умолчанию Django будет искать файл login.html в папке registration . Таким образом, нам нужно создать новую директорию под названием registration , а внутри нее создать необходимый HTML файл шаблона. Закройте локальный веб-сервера, используя в командной строке комбинацию Control+c . После этого введите следующее команды:

    Теперь наполните файл следующим контентом:

    Log In

    Теперь пользователь будет направлен на URL-маршрут который имеет название 'home' , который является домашней страницей.

    user account

    После ввода логина и пароля нашего аккаунта мы будем направлены на домашнюю страницу. Обратите внимание, что мы не добавляли никаких логических операции для представления и не создавали модели базы данных. Система аутентификации Django сама предоставляет все необходимое. Спасибо, Django!

    Данные пользователя на главной странице | is_authenticated

    Теперь нужно просто разместить следующий код в нужном месте нашего шаблона. Обновим файл base.html , вставив новый код под закрывающимся тегом .

    You are not logged in.

    После аутентификации, система поприветствует пользователя. В противном случае вы будете перенаправлены на страницу аутентификации.

    user account

    Домашняя страница после аутентификации

    Все сработало! Мое имя суперпользователя — wsv . Именно его я вижу на главной странице.

    Выход пользователя из профиля на Django

    Пользователь успешно прошел процедуру аутентификации, но… как теперь выйти? Можно было бы зайти в админку и выйти оттуда, однако есть способ получше. Добавим ссылку выхода, которая будет перенаправлять человека на домашнюю страницу. Благодаря системе аутентификации Django, добиться такого сценария проще простого.

    В файле шаблона base.html добавим ссылку для выхода сразу после приветствия пользователя.

    Вот и все, что от нас требуется, ведь само представление предоставляется приложением auth от Django. Правда, нам нужно уточнить, куда именно пользователь будет направлен после выхода из профиля.

    Обновим settings.py для создания ссылки перенаправления, которая будет называться LOGOUT_REDIRECT_URL . Мы можем добавить ее рядом с ссылкой для входа, таким образом файл должен выглядеть следующим образом:

    При обновлении домашней страницы можно увидеть, что у вошедших пользователей появилась ссылка для выхода «Log out«.

    Django выход пользователя

    Домашняя страница с ссылкой для выхода

    После нажатия на появившуюся ссылку, вы будете перенаправлены на домашнюю страницу, где покажется ссылка для входа.

    Домашняя страница вышедшего пользователя

    Попробуйте зайти и выйти несколько раз с вашим аккаунтом.

    Для регистрации новых пользователей также понадобится представление (views). В Django для этого предусмотрен класс формы UserCreationForm, который сильно упрощает работу. По умолчанию в нем присутствую три поля: username , password и password2 .

    Для создания надежной системы аутентификации предусмотрено множество способов организации кода и URL маршрутов. Сейчас мы создадим новое приложение accounts , специально для страницы регистрации.

    Затем новое приложение добавляется в переменную INSTALLED_APPS из файла settings.py .

    Далее добавляем новый URL маршрут в blog_project/urls.py , указывая на новое приложение прямо под тем местом, где мы включили приложение auth .

    Порядок URL маршрутов из переменной urlpatterns имеет значение, так как Django читает файл сверху вниз . Следовательно, когда создается запрос на URL-адрес /accounts/signup , Django вначале будет искать в django.contrib.auth.urls , и, не найдя такой, перейдет к приложению accounts.urls .

    Двигаемся далее и создаем файл accounts/urls.py .

    И добавляем в него следующий код:

    Мы используем пока не созданное представление под названием SignUpView , которое, если судить по наличию заглавных букв, является классовым представлением и имеет метод as_view() . Его URL-маршрут просто signup/ , так что полный URL-маршрут будет accounts/signup/ .

    Теперь перейдем к представлению, что использует встроенный класс UserCreationForm , и общий класс представления CreateView .

    Общий класс представления (generic) CreateView наследуется в классе SignUpView . Мы уточняем использование встроенного UserCreationForm и пока еще не созданного шаблона signup.html . Используем функцию reverse_lazy для перенаправления пользователя на страницу входа после успешной регистрации.

    Зачем использовать reverse_lazy вместо reverse ? Причина в том, что для всех общих классовых представлений URL не загружаются, когда имортируется файл. Поэтому нам нужно использовать функцию reverse_lazy для последующей загрузки URL, когда они будут доступны.

    Теперь создадим HTML файл шаблона signup.html в нашу директорию templates :

    После создания заполняем файл следующим кодом:

    Sign up

    Формат очень похож на тот, что мы делали ранее. В верхней части мы расширяем базовый шаблон base.html , помещаем логические операции между тегами , используем csrf_token в целях безопасности, отображаем содержимое формы используя form.as_p и добавляем кнопку подтверждения «Sign Up».

    Мы создали нового пользователя с именем «william» и после регистрации нас перенаправили на страницу входа. После успешного ввода имени и пароля мы были направлен на персонализированную домашнюю страницу с приветствием в формате «Hi ».

    Домашнаяя страница пользователя

    Домашняя страница пользователя william

    Поначалу многообразие путей развития проекта Django может запутать. Это нормально. Со временем все выстроится в логичную цепочку действий.

    Загружаем изменения на Github

    С нашего последнего git коммита прошло много времени. Давайте выполним коммит, а затем загрузим копию кода на GitHub. Для начала посмотрим на всю выполненную работу через команду git status .

    Python предоставляет инструментарий Tkinter для разработки приложений с графическим интерфейсом. Теперь дело за фантазией или необходимостью разработчика, что он / она хочет разработать с помощью этого инструментария. Давайте создадим простое информационное приложение с графическим интерфейсом, используя Tkinter. В этом приложении пользователь должен заполнить необходимую информацию, и эта информация автоматически записывается в файл Excel.

    Во-первых, создайте пустой файл Excel, после чего передайте в программе абсолютный путь к файлу Excel, чтобы программа могла получить доступ к этому файлу Excel.

    Ниже приведена реализация:

    from openpyxl import *

    from tkinter import *

    wb = load_workbook( 'C:\\Users\\Admin\\Desktop\\excel.xlsx' )

    sheet.column_dimensions[ 'A' ].width = 30

    sheet.column_dimensions[ 'B' ].width = 10

    sheet.column_dimensions[ 'C' ].width = 10

    sheet.column_dimensions[ 'D' ].width = 20

    sheet.column_dimensions[ 'E' ].width = 20

    sheet.column_dimensions[ 'F' ].width = 40

    sheet.column_dimensions[ 'G' ].width = 50

    sheet.cell(row = 1 , column = 1 ).value = "Name"

    sheet.cell(row = 1 , column = 2 ).value = "Course"

    sheet.cell(row = 1 , column = 3 ).value = "Semester"

    sheet.cell(row = 1 , column = 4 ).value = "Form Number"

    sheet.cell(row = 1 , column = 5 ).value = "Contact Number"

    sheet.cell(row = 1 , column = 6 ).value = "Email id"

    sheet.cell(row = 1 , column = 7 ).value = "Address"

    name_field.delete( 0 , END)

    course_field.delete( 0 , END)

    sem_field.delete( 0 , END)

    form_no_field.delete( 0 , END)

    contact_no_field.delete( 0 , END)

    email_id_field.delete( 0 , END)

    address_field.delete( 0 , END)

    if (name_field.get() = = "" and

    print ( "empty input" )

    sheet.cell(row = current_row + 1 , column = 1 ).value = name_field.get()

    sheet.cell(row = current_row + 1 , column = 2 ).value = course_field.get()

    sheet.cell(row = current_row + 1 , column = 3 ).value = sem_field.get()

    sheet.cell(row = current_row + 1 , column = 4 ).value = form_no_field.get()

    sheet.cell(row = current_row + 1 , column = 5 ).value = contact_no_field.get()

    sheet.cell(row = current_row + 1 , column = 6 ).value = email_id_field.get()

    sheet.cell(row = current_row + 1 , column = 7 ).value = address_field.get()

    Читайте также: