파이썬 배우기 - 중급 과정: 27일차, 입력 키 누르기 이벤트

Tkinter 입력 위젯에서 키 누르기 이벤트를 연구해 보겠습니다.




어제 우리는 더미 로그인 프로그램(비밀번호 관리자)을 만들었습니다. 그런데 문제는 비밀번호가 숨겨져 있었습니다. 비밀번호 데이터는 storepassword() 기능으로만 액세스할 수 있습니다. 하지만 오늘은 해커가 암호를 훔칠 수 있는 비밀 다락문을 만드는 것은 어떻습니까?

키 누르기 이벤트



암호 입력 위젯에 쓰는 모든 것을 스캔하고 명령 프롬프트에 인쇄하는 기본 프로그램에 코드 조각을 작성하여 이를 달성할 수 있습니다. 이는 keypress 이벤트를 사용하여 수행할 수 있습니다. e1.bind("<Key>",keypress) 아무 키나 누를 때마다 'keypress' 기능이 실행됩니다.

전체 코드는 다음과 같습니다.

from tkinter import *
spy=Tk()
spy.geometry("300x200")
spy.title("spyware")
def keypress(event):
    try:
        print(ord(event.char),end=".")
    except: # for blank press
        pass
e1=Entry(spy,show='*')
e1.focus_set()
e1.bind("<Key>",keypress)
# mind the case of 'key'- k must be K
e1.pack()
spy.mainloop()







그래서 무슨 일이 일어나고 있습니까? 글쎄, 실제 작업은 쉘 창에서 발생합니다.



키 누르기 기능이 무엇인지 설명하겠습니다. 아무 키나 누를 때마다 키 누르기 기능이 실행됩니다. 이 함수는 먼저 어떤 키가 눌렸는지 추출합니다. 그런 다음 키를 ASCII 값으로 변환하고 구분을 위해 점을 사용하여 명령 셸에 인쇄합니다. 이렇게 하면 백스페이스 및 Enter 키와 같은 문자도 감지할 수 있습니다. 암호를 얻기 위해 이 문자열을 구문 분석하는 것은 해커에게 식은 죽 먹기입니다😈

The code is wrapped in try-except to prevent blank key presses, which results in errors like

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\aatma\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1884, in __call__
    return self.func(*args)
  File "C:/Users/aatma/AppData/Local/Programs/Python/Python310/spy.py", line 6, in keypress
    print(ord(event.char),end=".")
TypeError: ord() expected a character, but string of length 0 found



이제 암호 관리자와 코드를 연결하고 결과를 확인하겠습니다.

import tkinter as tk # import the Tkinter module

form=tk.Tk() # create the blank window.
form.title("password manager") # set the title as password manager
form.geometry('400x200') # set the default geometry of the window.

TB1=tk.Entry(form, width = 20) 
# make an entry widget with 20 spaces for the username

TB2=tk.Entry(form,show="*", width = 20)
def keypress(event):
    try:
        print(ord(event.char),end=".")
    except: # for blank press
        pass
TB2.bind("<Key>",keypress)
# entry widget for password and hide the keys whenever pressed.

# TB1 is for username, TB2 is for password
TB1.pack()
TB2.pack()
# pack the widgets into 'form'

label=tk.Label(form,text="")
# make a label to display the username

def show(): #function to be executed once the button is pressed.
    a=TB1.get() # get username
    b=TB2.get() # get password
    if(a!="" and b!=""):
     label.config(text="Welcome "+a+" to python GUI",fg="Green") # display the label
     storepassword(a,b) # store password and username
    else:
     label.config(text="Please enter a valid username and password.",fg="Red")  # blank screens

def storepassword(username, password):
    #//Some mechanism to store password//
    pass #stubbed

button=tk.Button(form,text="Sign Up", command=show) # setup the button
button.pack()
label.pack()
form.mainloop()
show()






그래서 친구들은 오늘이 전부였습니다. 업데이트를 계속 지켜봐주십시오.....

좋은 웹페이지 즐겨찾기