Рубрики
Без рубрики

Сделать пароль защищенный виртуальный журнал, используя Tkinter, Python

Введение: с помощью Python я пытался воссоздать радость поддержания … Теги с Python, учебником, программированием, ментальным здоровьем.

Введение:

С помощью Python я пытался воссоздать радость поддержания журнала (практически). Люди часто не нахожу время для поддержания физического дневника или журнала в эти дни. Этот виртуальный журнал будет обслуживать их хорошо и хорошо, так как это так же эффективно, как физическая. Функция защиты паролей дает привилегию открытия приложения только пользователем. (Я написал этот блог с предположением, что у вас есть базовые знания о Tkinter и Python; если не учиться и пересмотреть блог.)

Используемые модули:

Основные модули используются ” Tkinter “(для создания GUI),« ОС »(для файлов OpenIG) .additional к этим я создал три (пользовательские) модули именно« write_func »,” read_func “,« edit_func »для выполнения нужных операций.

Объяснение структуры кода:

Я разбил всю целую программу на четыре разных файла (три пользовательских пользовательских модуля и одна основная программа).

Основная программа:

Основная программа содержит функцию защиты паролем, и она служит основой для нашего проекта, импортируя другие пользовательские модули. Код для основной программы следующий: (я объяснил, что это функциональная линия по линии в коде, пожалуйста, обратитесь)

#Modules used 
 #These modules are inbuilt python modules.
from tkinter import*
from tkinter import messagebox
import os
import time

#These modules are user defined python modules.Each module has its own function.
import write_func
import read_func
import edit_func

def directory():
    '''This function sets the directory to the defined path.This path 
    is where all your files will be saved.'''
    path="#path"
    os.chdir(path)
directory()

class login_interface(Frame):
    '''This class contains the login section of the app.The user have 
    to enter a password to access the main application.'''
    def __init__(self,master=None):
        #initiating the frame
        Frame.__init__(self,master)
        self.master=master
        self.security()

    #function that holds the widgets of login window
    def security(self):
        self.master.title("LOGIN")
        self.pack(fill=BOTH, expand=1)
        lbl = Label(self, text="PASSWORD").grid(column=0, row=0)

        # Entry to get a input from the user
        self.pwrd = Entry(self,show="*")
        self.pwrd.focus_set()
        self.pwrd.grid(column=1, row=0)

        #login button binded to a function named login
        login = Button(self, text="login", width=20,command=self.login)
        login.grid(column=1, row=2)


    def login(self):
        '''this function which is binded to the "login" Button checks if the
        password given by the user.If it is correct it directs the user to main application'''

        #if the password given is correct the following get executed
        if self.pwrd.get()=="#Your_password":
            #destroys the present login window
            a.destroy()

            #initiates the main application
            b=Tk()
            b.geometry("500x500")
            app_b=journal(b)  #journal is a class mention bellow
            app_b.mainloop()  #mainloop for the program should run until we close
                              #Note  this is the mainloop of our main application

        #if the given password is wrong then an error is shown
        else:
            messagebox.showinfo("ERROR ","retry wrong password")

class journal(Frame):
    '''this class contains the frame and widgets which make up the main application.
    Main application contains three buttons Write,read,Edit respectively.'''

    #initating frame of window
    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.master=master

        self.master.title("DIARY")
        self.pack(fill=BOTH, expand=1)

        #write button binded to write function.
        write_button=Button(self,text="Write",width=100,height=10,command=self.write)
        write_button.pack()

        #Read button binded to read function.
        read_button=Button(self,text="Read",width=100,height=10,command=self.read)
        read_button.pack()

        #Edit button binded to edit function.
        edit_button=Button(self,text="Edit",width=100,height=10,command=self.edit)
        edit_button.pack()

    def write(self):
        '''this function calls the function defined in the "write_func" module.This module is an user defined module.
        This module enables user to write their thoughts and save it in the respective directory.'''

        a=Tk()
        B=write_func.window(a)
        B.mainloop()

    def read(self):
        '''This function calls the function defined in the "read_func" module.This module is an user defined module.
        This module enables user to read the files they have saved previously.'''

        a=Tk()
        B=read_func.window(a)
        B.mainloop()        

    def edit(self):
        '''this function calls the function defined in the "edit_func" module.This module is an user defined module.
        This module enables the user to revisit and edit the files they have saved previously.'''

        a=Tk()
        B=edit_func.window(a)
        B.mainloop()


'''Creating the instance of the login class and running the program'''
a=Tk()
a.geometry("250x50")
app=login_interface(a)
app.mainloop()    

Выход этого кода будет таким:

После ввода правильного пароля открывается основное приложение

Как вы можете видеть, главное приложение содержит три кнопки, а именно: «Написать», «Читать», «Редактировать». Кнопка «запись» связана с модулем «write_func». Точно так же кнопка «read» и «Edit» связана с модулями «READ_FUNC» и «Edit_Func» соответственно.

write_func:

Эти модули открывают графический интерфейс, позволяющий пользователю писать (введите) по его/ее мысли и сохранить его как файл «.txt» в месте (внутри локального устройства), указанному пользователем. Ниже приведен код для этого модуля:

#moules imported
from tkinter import*
import time
import os
from tkinter import messagebox

def directory():
    '''This function sets the directory to the defined path.This path 
    is where all your files will be saved.'''
    path="#Path"
    os.chdir(path)
directory()



class window(Frame):
    '''This class contains the widgets that will allow user to write into files'''
    def __init__(self,master=None):
        #intialisation of the frame
        Frame.__init__(self,master)
        self.master=master
        self.master.title("Diary")
        title=Label(self.master,text="Title").pack()

        #Entry box to get titile of the file from the user.
        self.title_box=Entry(self.master)
        self.title_box.pack()

        scrollbar=Scrollbar(self.master).pack(side=RIGHT,fill=Y)#scrollbar
        Label(self.master,text="Content").pack()

        #Text for the user to write his thoughts
        self.content_box=Text(self.master)
        self.content_box.pack()

        #This button is binded to the function "save_file" wich saves the file in the specified path'''
        save_button=Button(self.master,text="Save",width=10,command=self.save_file).pack()

    def save_file(self):
        '''This function saves the content written by the user as a text file'''

        localtime=time.asctime(time.localtime(time.time()))
        date=localtime[8:11]
        month=localtime[4:7]
        year=localtime[20:24]
        file_name=self.title_box.get()+" "+date+month+year+".txt"
        f=open(file_name,"w+")
        f.write(self.content_box.get("1.0",END))
        messagebox.showinfo("Diary","Your file is saved successfully!! ")

Когда нажата кнопка «запись» в основном приложении, она будет генерировать следующий выход:

read_func:

Этот модуль генерирует интерфейс, который позволяет пользователю открывать и прочитать его предыдущие зажигания. Ниже приведен код для этого:

#modules imported
from tkinter import*
import os
from tkinter import messagebox


class window(Frame):
    '''This class contains the widgets that allows the user to read the files stored previously'''
    def __init__(self,master=None):
        #intilisation of the frame
        Frame.__init__(self,master)
        self.master=master
        self.master.title("Diary")
        self.master.geometry("400x300")

        #Display all the files present in the directory
        Label(self.master,text="Select a file").pack(side=TOP)
        path="#path"
        self.file_names=os.listdir(path)
        self.srch_box=Entry(self.master)
        self.srch_box.pack()
        file_list=Listbox(self.master)
        file_list.pack()
        for i in range(0,len(self.file_names)):
            a=str(i+1)+") "+self.file_names[i]
            file_list.insert(END,a)

        #Read button binded to the function "read_file" which displays the content in the file.
        read_button=Button(self.master,text="Read",width=20,command=self.read_file).pack(side=BOTTOM)
    def read_file(self):
        self.file_name=self.srch_box.get()

        '''If the specified file is present it is displayed in a text
         for the user to read.If the specified file is not present it 
         displays an error'''
        if(self.file_name in self.file_names ):
            f=open(self.file_name,"r")
            contents=f.read()
            read_window=Tk()
            read_window.title(self.file_name)
            t=Text(read_window)
            t.pack()
            t.insert("end",contents)
            t.config(state=DISABLED)
            read_window.mainloop()
        else:
            messagebox.showinf0("Diary","File doesn't exist")

Когда нажата кнопка «чтение» в основном приложении, она будет генерировать следующий выход:

Когда пользователь вводит имя файла, которое он/она желает прочитать, будет отображаться ему/ее таким образом:

edit_func:

Эти модули позволяют пользователю пересмотреть любые файлы и редактировать содержимое в нем. Код для этого является следующим:

#Modules imported
from tkinter import*
import os
from tkinter import messagebox


class window(Frame):
    '''This class contains the widgets that allows the user to edit the file saved previously'''

    def __init__(self,master=None):
        #intitialsation of frame
        Frame.__init__(self,master)
        self.master.title("Diary")
        self.master.geometry("400x300")

        #Diplaying the files in the path for the user to select.
        Label(self.master,text="Select a file").pack()
        path="C:/Users/Dhanalakshmi/journal"
        self.file_names=os.listdir(path)
        self.srch_box=Entry(self.master)
        self.srch_box.pack()
        file_list=Listbox(self.master)
        file_list.pack()
        for i in range(0,len(self.file_names)):
            a=str(i+1)+") "+self.file_names[i]
            file_list.insert(END,a)

        #Edit button binded with "edit_File" function which allows user to edit the selected file.
        edit_button=Button(self.master,text="Edit File",width=20,command=self.edit_file).pack()


    def edit_file(self):
        '''This function opens the file specified by the user to edit it.If the file is not present then it shows an error '''
        self.file_name=self.srch_box.get()
        if(self.file_name in self.file_names ):
            f=open(self.file_name,"r")
            content=f.read()
            edit_window=Tk()
            t=Text(edit_window)
            t.pack()
            edit_window.title(self.file_name)
            t.insert("end",content)

            #Saves the edited file.
            def save_file():
                F=open(self.file_name,"w+")
                F.write(t.get("1.0",END))
                messagebox.showinfo("Diary","Your file is saved successfully")
            save_button=Button(edit_window,text="Save",command=save_file).pack()
        else:
            messagebox.showinfo("Diary","File doesn't exist")

Когда нажата кнопка «Редактирование» в основном приложении, она будет генерировать следующий вывод:

Когда пользователь вводит имя файла, которое он/она желает редактировать, будет отображаться ему/ей в этом порядке:

Изряд, что эти пользовательские модули определены в том же каталоге, что и в основной программе. Я также дал ссылку на REPO GitHUB этого проекта. После указанных инструкций вы сможете создать простое «Журнал защищенного паролем журнала». Спасибо за то, что нужно прочитать мой блог, если у вас есть какие-либо вопросы, упомяну об этом в комментариях.

GitHub Link: https://github.com/mshrish/digital-diary.

Оригинал: “https://dev.to/mshrish/making-a-password-protected-virtual-journal-using-tkinter-python-41d2”