1. 程式人生 > >project3_NeedToLoginCalculator(需要進行登陸確認的計算器)

project3_NeedToLoginCalculator(需要進行登陸確認的計算器)

round 位數 老師 ont 登錄 選項 pen exc !=


下列實現代碼說明:
  下列代碼主要是實現計算器功能。由於之前在莫凡老師開設的《用 python 和 tkinter 做簡單的窗口視窗》課程當中學習了tkinter的內容,在該課程的結束部分是老師帶著做一個關於
登錄窗口的小程序。
  在學習了該課程後,自己又去學習了計算器編寫的代碼,而後,想著能否把這兩個小項目結合寄來,於是,新的一個小項目又誕生了。
  該程序的功能是在打開計算器程序之前需要進行一個登陸操作。
  該項目涉及到的前面的project如下:

  1、class13and14and15_登錄窗口 - JY小腳丫 - 博客園

    https://www.cnblogs.com/jyfootprint/p/9571509.html

  2、project1_calculator(使用tkinter實現python計算器,含有具體過程與註釋) - JY小腳丫 - 博客園

    https://www.cnblogs.com/jyfootprint/p/9570951.html

代碼如下:






#!/usr/bin/env python # -*- coding:utf-8 -*- # ------------------------------------------------------------ import calculator import tkinter as tk from tkinter import messagebox import pickle window = tk.Tk() window.title("登錄窗口") window.maxsize(460, 300) window.minsize(460, 300) # welcom image canvas = tk.Canvas(window, width=500, height=200) image_file = tk.PhotoImage(file=‘my_login.gif‘) # 10, 0 表示錨點的橫,縱位置; anchor=‘nw‘表示錨點的位置是左上角 image = canvas.create_image(10, 0, anchor=‘nw‘, image=image_file) canvas.pack(side=‘top‘) tk.Label(window, text=‘username:‘, font=(‘黑體‘, 12)).place(x=60, y=160, anchor=‘nw‘) tk.Label(window, text=‘password:‘, font=(‘黑體‘, 12)).place(x=60, y=190, anchor=‘nw‘) # 設置存儲的變量 username = tk.StringVar() password = tk.StringVar() # 設置登錄的輸入框,並獲取信息 entry_username = tk.Entry(window, textvariable=username, width=30).place(x=150, y=160, anchor=‘nw‘) entry_password = tk.Entry(window, textvariable=password, width=30, show=‘*‘).place(x=150, y=190, anchor=‘nw‘) # 初始化 username 的信息 username.set(‘[email protected]‘) def usr_login(): usr_name = username.get() usr_password = password.get() try: with open(‘usrs_info.pickle‘, ‘rb‘) as usr_file: usrs_info = pickle.load(usr_file) except FileNotFoundError: usrs_info = {‘admin‘: ‘admin‘} pickle.dump(usrs_info, usr_file) if usr_name in usrs_info: if usr_password == usrs_info[usr_name]: messagebox.showinfo(title=‘Welcom‘, message=‘Welcome to log in! \n‘+ usr_name) window.destroy() calculator.Calculator() else: messagebox.showerror(title=‘Error‘, message=‘Password Error!\nTry again!!‘) else: is_sign_up = messagebox.askyesno(title=‘Ask‘, message=‘You have not sign up yet.\nSign up now?‘) if is_sign_up is True: usr_sign_up() def usr_sign_up(): # 設置窗口 window_sign_up = tk.Toplevel(window) window_sign_up.title(‘Sign up window‘) window_sign_up.maxsize(460, 180) window_sign_up.minsize(460, 180) # 設置標簽 tk.Label(window_sign_up, text=‘username:‘, font=(‘黑體‘, 12)).place(x=30, y=30, anchor=‘nw‘) tk.Label(window_sign_up, text=‘password:‘, font=(‘黑體‘, 12)).place(x=30, y=60, anchor=‘nw‘) tk.Label(window_sign_up, text=‘confirm password:‘, font=(‘黑體‘, 12)).place(x=30, y=90, anchor=‘nw‘) # 設置輸入框 # 設置存儲的變量 usr_username = tk.StringVar() usr_password1 = tk.StringVar() usr_password2 = tk.StringVar() # 設置登錄的輸入框,並獲取信息 usr_entry_username = tk.Entry(window_sign_up, textvariable=usr_username, width=40).place(x=170, y=30, anchor=‘nw‘) usr_entry_password1 = tk.Entry(window_sign_up, textvariable=usr_password1, width=40, show=‘*‘).place(x=170, y=60, anchor=‘nw‘) usr_entry_password2 = tk.Entry(window_sign_up, textvariable=usr_password2, width=40, show=‘*‘).place(x=170, y=90, anchor=‘nw‘) # 初始化 username 的信息 usr_username.set(‘[email protected]‘) def new_sign_up(): new_name = usr_username.get() new_password = usr_password1.get() new_password_confirm = usr_password2.get() # 打開配置文件,查看註冊的信息是否在文件中 with open(‘usrs_info.pickle‘, ‘rb‘) as usr_file: exist_usr_info = pickle.load(usr_file) # 對比用戶名是否已經儲存在文件中 if new_name in exist_usr_info : messagebox.showerror(title=‘Error‘,message=‘The user has already signed up!‘) else: if new_password != new_password_confirm: messagebox.showerror(title=‘Error‘, message=‘Password and confirm password must be the same!‘) else: exist_usr_info[new_name] = new_password with open(‘usrs_info.pickle‘, ‘wb‘) as usr_file: # 寫入到文件中 pickle.dump(exist_usr_info, usr_file) messagebox.showinfo(title=‘Welcome‘, message=‘You have successfully signed up!‘) window_sign_up.destroy() # 設置註冊的按鈕 tk.Button(window_sign_up, text=‘sign up‘, command=new_sign_up).place(x=220, y=120, anchor=‘nw‘) tk.Button(text=‘login‘, command=usr_login).place(x=170, y=220, anchor=‘nw‘) tk.Button(text=‘sign up‘, command=usr_sign_up).place(x=240, y=220, anchor=‘nw‘) window.mainloop()

  



上面代碼說明:

語句:  import calculator 
說明:  calculator 是一個自己編寫的一個名稱為“calculator.py"文件,是用來實現計算器計算功能程序,該程序的內容見一下轉接鏈接
代碼內容如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# ------------------------------------------------------------
# ------------------------------------------------分割線-------------------------------------------------
‘‘‘
# ------------------------------------------------------------
# # 7、(完成全部設計)實現基本的計算器功能,補充錯誤檢測, 修改‘C’為清楚功能, ‘<==‘為後退功能
# # # 改動位置位置:    def click_button(self, event):
# ------------------------------------------------------------
‘‘‘

class Calculator:
    import tkinter as tk
    import tkinter.messagebox as mbox

    def __init__(self):
        # 生成一個窗口對象
        self.window = self.tk.Tk()
        # 命名窗口對象的顯示title
        self.window.title(‘計算器‘)
        # 設置窗口的大小 minsize最小   maxsize最大
        self.window.minsize(240, 290)
        self.window.maxsize(240, 290)
        # 是否清空顯示框判定參數
        # 設置菜單
        self.set_menu()
        # 設置顯示框
        self.label_show = self.tk.Label(text=‘‘, anchor=‘se‘, font=(‘黑體‘, 30), fg=‘black‘)
        self.label_show.place(x=0, y=0, width=240,height=80)
        # 設置按鈕組件
        self.set_buttons()
        # 將窗口放入主消息隊列
        self.window.mainloop()

    def set_menu(self):
        ‘‘‘
        設置菜單
        :return: None
        ‘‘‘
        # 創建總菜單
        menubar = self.tk.Menu(self.window)
        # 創建一個下拉菜單,並且加入文件菜單
        filemenu = self.tk.Menu(menubar, tearoff=False)
        # 創建菜單中的選項
        filemenu.add_command(label=‘退出計算器‘, command=self.window.quit )

        # print author的函數
        def show_author():
            self.mbox.showinfo(title=‘作者信息‘,message=‘作者:許建榮\n聯系郵箱:[email protected]‘)

        filemenu.add_command(label=‘作者信息‘, command=show_author)
        # 將文件菜單作為下拉菜單添加到總菜單中,並且將命名為操作
        menubar.add_cascade(label=‘查看‘, menu=filemenu)
        # 顯示總菜單
        self.window.config(menu=menubar)


    def set_buttons(self):
        # 基礎坐標,  x0, y0,開始坐標; x_width, y_width 間隔
        x0, y0, x_width, y_width,height = 0, 90, 60, 40, 40
        # 7
        btn7 = self.tk.Button(text=‘7‘, bd=2, font=‘黑體‘)
        btn7.place(         x=x0,           y=y0,               width=x_width,  height=y_width)
        # 8
        btn8 = self.tk.Button(text=‘8‘, bd=2, font=‘黑體‘)
        btn8.place(         x=x0+x_width*1, y=y0,               width=x_width,  height=y_width)
        # 9
        btn9 = self.tk.Button(text=‘9‘, bd=2, font=‘黑體‘)
        btn9.place(         x=x0+x_width*2, y=y0,               width=x_width,  height=y_width)
        # +
        btn_add = self.tk.Button(text=‘+‘, bd=2, font=‘黑體‘)
        btn_add.place(      x=x0+x_width*3, y=y0,               width=x_width,  height=y_width)

        # 4
        btn4 = self.tk.Button(text=‘4‘, bd=2, font=‘黑體‘)
        btn4.place(         x=x0,           y=y0+y_width,       width=x_width,  height=y_width)
        # 5
        btn5 = self.tk.Button(text=‘5‘, bd=2, font=‘黑體‘)
        btn5.place(         x=x0+x_width*1, y=y0+y_width,       width=x_width,  height=y_width)
        # 6
        btn6 = self.tk.Button(text=‘6‘, bd=2, font=‘黑體‘)
        btn6.place(         x=x0+x_width*2, y=y0+y_width,       width=x_width,  height=y_width)
        # -
        btn_subtract = self.tk.Button(text=‘-‘, bd=2, font=‘黑體‘)
        btn_subtract.place( x=x0+x_width*3, y=y0+y_width,       width=x_width,  height=y_width)

        # 1
        btn1 = self.tk.Button(text=‘1‘, bd=2, font=‘黑體‘)
        btn1.place(         x=x0,           y=y0+y_width*2,     width=x_width,  height=y_width)
        # 2
        btn2 = self.tk.Button(text=‘2‘, bd=2, font=‘黑體‘)
        btn2.place(         x=x0+x_width*1, y=y0+y_width*2,     width=x_width,   height=y_width)
        # 3
        btn3 = self.tk.Button(text=‘3‘, bd=2, font=‘黑體‘)
        btn3.place(         x=x0+x_width*2, y=y0+y_width*2,     width=x_width,   height=y_width)
        # *
        btn_mutiply = self.tk.Button(text=‘*‘, bd=2, font=‘黑體‘)
        btn_mutiply.place(  x=x0+x_width*3, y=y0+y_width*2,     width=x_width,   height=y_width)

        # 0
        btn0 = self.tk.Button(text=‘0‘, bd=2, font=‘黑體‘)
        btn0.place(         x=x0,           y=y0+y_width*3,     width=x_width*2, height=y_width)
        # .
        btn_point = self.tk.Button(text=‘.‘, bd=2, font=‘黑體‘)
        btn_point.place(    x=x0+x_width*2, y=y0+y_width*3,     width=x_width,   height=y_width)
        # /
        btn_divid = self.tk.Button(text=‘/‘, bd=2, font=‘黑體‘)
        btn_divid.place(    x=x0+x_width*3, y=y0+y_width*3,     width=x_width,   height=y_width)

        # C後退
        btn_clear = self.tk.Button(  text=‘C‘, bd=2, font=‘黑體‘)
        btn_clear.place(     x=x0,           y=y0+y_width*4,     width=x_width, height=y_width)

        # C後退
        btn_back = self.tk.Button(  text=‘<==‘, bd=2, font=‘黑體‘)
        btn_back.place(     x=x0+x_width*1,           y=y0+y_width*4,     width=x_width, height=y_width)

        # =
        btn_equal = self.tk.Button( text=‘=‘, bd=2, font=‘黑體‘)
        btn_equal.place(    x=x0+x_width*2, y=y0+y_width*4,     width=x_width*2, height=y_width)

        # 綁定Button的點擊事件
        btn7.bind_class(‘Button‘, ‘<Button-1>‘, self.click_button)

    def click_button(self, event):

        # 獲取點擊的按鈕信息信息
        input_event = event.widget[‘text‘]
        # 輸入的按鈕信息顯示
        self.label_show[‘text‘] = self.label_show[‘text‘] + input_event
        # 異常捕獲
        try:
            # 計算符號
            cal_symbol = [‘+‘, ‘-‘, ‘*‘, ‘/‘]
            # 判定運算符號重復的時候,使用最後輸入的符號
            if self.label_show[‘text‘][-1] in cal_symbol and self.label_show[‘text‘][-2] in cal_symbol:
                # 取重復符號前面的內容
                header = self.label_show[‘text‘][:-2]
                footer = self.label_show[‘text‘][-1]
                self.label_show[‘text‘] = header + footer
        except:
            pass

        # 進行普通計算
        if event.widget[‘text‘] == ‘=‘:
            # 異常捕獲
            try:
                res_bit = 2  # 計算保留的位數
                res = eval(self.label_show[‘text‘][:-1])  # 計算點擊 “=” 之前的計算表達式
                # print(type(res))
                self.label_show[‘text‘] = str(round(float(res), res_bit))
            except ZeroDivisionError:
                # 除法時,除數不能為0
                self.mbox.showerror(title=‘錯誤‘, message=‘除法計算時!除數不能為0!‘)
            except:
                self.mbox.showerror(title=‘未知名錯誤‘, message=‘算式錯誤,請檢查!‘)

        elif event.widget[‘text‘] == ‘<==‘:
            # 點擊的‘<==’也計算在內,它占3個字符,因此是倒數4位去掉
            back_res = self.label_show[‘text‘][:-4]
            self.label_show[‘text‘] = back_res

        elif event.widget[‘text‘] == ‘C‘:
            # 點擊的‘C’也計算在內,因此是倒數2位去掉
            self.label_show[‘text‘] = ‘‘

if __name__==‘__main__‘:
    start = Calculator()

  

project3_NeedToLoginCalculator(需要進行登陸確認的計算器)