LoginSignup
16
11

More than 5 years have passed since last update.

Pythonで簡単パスワードボックス

Last updated at Posted at 2015-10-24

背景

Pythonのコマンドを実行した際にユーザのパスワード入力が必要になったため,簡単なコードでパスワードを入力するポップアップを作りました.

参考

Tkinterは情報が少なく,ちょっと使い勝手が悪いのですが,nnahitoさんの投稿がよくまとまっているので,参考になると思います.

コード

動作は python 2.7.10で行いました.Tkinterはpython標準で組み込まれているので,特にインストールは必要ありません.
最小限のコードにしたため,GUIを変更したい場合は以下のコードに変更を加えてください.

# -*- coding: utf-8 -*-
import Tkinter

class PswdBox(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        self.title('Enter password')
        self.ent = Tkinter.Entry(self, show='*')
        self.ent.pack()
        self.lbl = Tkinter.Label(self, foreground='#ff0000')
        self.lbl.pack()
        self.btn = Tkinter.Button(self, text='Submit', command=self.submit)
        self.btn.pack()
        # ここで正しいパスワードを定義 あるいは ファイルからインポートなどする
        self.correct_pass = 'pass'

    def submit(self):
        self.pswd = self.ent.get()
        if self.pswd == self.correct_pass: # 正しい
            self.destroy() # ウィンドウを閉じる
        else: # 間違え
            self.lbl['text'] = 'Try again!'
            print(self.pswd)


if __name__ == '__main__':
    pb = PswdBox()
    pb.mainloop()
    print(pb.pswd)

実行結果

使い方
上のコードを適当に pswdbox.pyとデスクトップに保存してターミナルで

python ~/Desktop/pswdbox.py

と入力すれば起動します.
パスワードボックス実行結果

16
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11