1. 程式人生 > 其它 >2021-2022-1 20211420《資訊保安專業導論》使用python的tkinter庫製作一個簡易計算器

2021-2022-1 20211420《資訊保安專業導論》使用python的tkinter庫製作一個簡易計算器

參考文章

如何利用python的tkinter實現一個簡單的計算器
通過學習這篇文章,我學會了如何用tkinter庫製作一個簡易計算器

設計思路

首先一個計算器最基本的是視窗和按鈕
所以可以先定義一個視窗並設定輸入框的內容

equal_is = False
txtchange=''        #設定輸入框的內容
#建立窗體
window = tk.Tk()
window.geometry('250x350')
window.title('簡易計算器')

然後再用函式定義按鈕和生成按鈕

#定義空函式,在沒有賦值的時候輸出為text
def create_button(text, col, row, cs, rs, print='', px=(1, 1), py=(1, 1)):  #建立函式生成按鈕
    if print == '':
        t = text
    else:
        t = print
    a = tk.Button(window, text=text , width=4, command=lambda:(text_print(t)))    #輸入內容
    a.grid(column=col, row=row, columnspan=cs, rowspan=rs, padx=px, pady=py, sticky='nswe')
    return (a)

#定義函式自動填充行和列
def grid_rowconfigure(*rows):        #函式填充行。 *rows:允許接收多個引數
    for i in rows:
        window.grid_rowconfigure(i, weight=1)

def grid_columnconfigure(*cols):        #函式填充列。 *cols:允許接收多個引數
    for i in cols:
        window.grid_columnconfigure(i, weight=1)

grid_rowconfigure(2, 3, 4, 5)
grid_columnconfigure(0, 1, 2, 3, 4)

上面的程式碼塊是用來規範主窗體,下面的程式碼塊是生成輸入框和顯示框和建立按鈕

#生成輸入框
printf=tk.Label(window, text='', bg='white', fg='black', font=('宋體',24), anchor='w', relief='flat')
printf.grid(column=0, row=0, columnspan=5, rowspan=1, sticky='we')
#生成顯示框
displayf=tk.Label(window, bg='white', fg='grey', height=1, font=('宋體',22), anchor='w', relief='flat')
displayf.grid(column=0, row=1, columnspan=5, rowspan=1, sticky='we')
#生成按鈕
button = {}
button['1'] = create_button('1', 0, 4, 1, 1)
button['2'] = create_button('2', 1, 4, 1, 1)
button['3'] = create_button('3', 2, 4, 1, 1)
button['4'] = create_button('4', 0, 3, 1, 1)
button['5'] = create_button('5', 1, 3, 1, 1)
button['6'] = create_button('6', 2, 3, 1, 1)
button['7'] = create_button('7', 0, 2, 1, 1)
button['8'] = create_button('8', 1, 2, 1, 1)
button['9'] = create_button('9', 2, 2, 1, 1)
button['0'] = create_button('0', 0, 5, 1, 1)

button['.'] = create_button('.', 1, 5, 1, 1)
button['='] = create_button('=', 4, 5, 1, 1)
button['+'] = create_button('+', 3, 3, 1, 1)
button['-'] = create_button('-', 3, 4, 1, 1)
button['*'] = create_button('×', 3, 5, 1, 1, print='*')
button['/'] = create_button('÷', 4, 4, 1, 1, print='/')
button['←'] = create_button('←', 4, 3, 1, 1)

button['C'] = create_button('C', 2, 5, 1, 1)
button['('] = create_button('(', 3, 2, 1, 1)
button[')'] = create_button(')', 4, 2, 1, 1)

然後需要我們繫結鍵盤事件

#繫結鍵盤事件
def bind_print(event):                              #函式鍵盤事件輸入算式
    global textchange, equal_is
    if event.keysym != 'Return':
        if event.keysym == 'BackSpace':             #如果按鍵名為backspace,那就退格
            a = str(textchange)[0:-1]
            textchange = a
        elif event.keysym == 'Delete':              #清空
            textchange = ''
        else:
            textchange = str(textchange) + str(event.char)  #輸入按鍵內容,char不會獲得Ctrl,Shift等特殊按鍵的文字
        printf.configure(text=textchange)           #顯示內容
        show_is()                                   #判斷是否錯誤
        equal_is = False
    else:
        text_equal()
#繫結鍵盤事件
window.bind('<Key>', bind_print)                    #當鍵盤按下任意鍵,執行bind_print

最後就需要定義函式操作計算過程,程式碼如下

#定義輸入和計算函式
def text_print(x):          #函式按鈕輸入算式
    global textchange,equal_is
    if x != '=':
        if x == '←':
            a = str(textchange)[0:-1]
            textchange = a              #退格
        elif x == 'C':
            textchange = ''             #清空
        else:
            textchange = str(textchange) + str(x)   #輸入
        printf.configure(text=textchange)
        show_is()
        equal_is=False                  #判斷格式有無錯誤
    if x == '=':
        text_equal()                    #計算結果

#計算結果
def text_equal(event=None):                         #函式計算結果並顯示在輸入框
    global textchange, equal_is                     #宣告全域性變數
    if displayf['text'] != '錯誤' and equal_is == False:
        textchange = displayf['text']               #無格式錯誤時,計算結果
        printf.configure(text=textchange)           #輸入框顯示結果
        displayf.configure(text='')                 #清空顯示框
        equal_is = True

def show_is():                          #顯示框內容
    global textchange                   #宣告全域性變數
    if textchange != '':
        try:
            textshow = eval(textchange)
        except(SyntaxError, TypeError, NameError):
            displayf.configure(text='錯誤')           #出錯顯示
        else:
            displayf.configure(text=textshow)       #沒出錯顯示結果
    else:
        displayf.configure(text='')                 #輸入框為空就清空顯示框

完整程式碼以及執行結果

import tkinter as tk

#定義空函式,在沒有賦值的時候輸出為text
def create_button(text, col, row, cs, rs, print='', px=(1, 1), py=(1, 1)):  #建立函式生成按鈕
    if print == '':
        t = text
    else:
        t = print
    a = tk.Button(window, text=text , width=4, command=lambda:(text_print(t)))    #輸入內容
    a.grid(column=col, row=row, columnspan=cs, rowspan=rs, padx=px, pady=py, sticky='nswe')
    return (a)

#定義函式自動填充行和列
def grid_rowconfigure(*rows):        #函式填充行。 *rows:允許接收多個引數
    for i in rows:
        window.grid_rowconfigure(i, weight=1)

def grid_columnconfigure(*cols):        #函式填充列。 *cols:允許接收多個引數
    for i in cols:
        window.grid_columnconfigure(i, weight=1)

#繫結鍵盤事件
def bind_print(event):                              #函式鍵盤事件輸入算式
    global textchange, equal_is
    if event.keysym != 'Return':
        if event.keysym == 'BackSpace':             #如果按鍵名為backspace,那就退格
            a = str(textchange)[0:-1]
            textchange = a
        elif event.keysym == 'Delete':              #清空
            textchange = ''
        else:
            textchange = str(textchange) + str(event.char)  #輸入按鍵內容,char不會獲得Ctrl,Shift等特殊按鍵的文字
        printf.configure(text=textchange)           #顯示內容
        show_is()                                   #判斷是否錯誤
        equal_is = False
    else:
        text_equal()

#定義輸入和計算函式
def text_print(x):          #函式按鈕輸入算式
    global textchange,equal_is
    if x != '=':
        if x == '←':
            a = str(textchange)[0:-1]
            textchange = a              #退格
        elif x == 'C':
            textchange = ''             #清空
        else:
            textchange = str(textchange) + str(x)   #輸入
        printf.configure(text=textchange)
        show_is()
        equal_is=False                  #判斷格式有無錯誤
    if x == '=':
        text_equal()                    #計算結果

#計算結果
def text_equal(event=None):                         #函式計算結果並顯示在輸入框
    global textchange, equal_is                     #宣告全域性變數
    if displayf['text'] != '錯誤' and equal_is == False:
        textchange = displayf['text']               #無格式錯誤時,計算結果
        printf.configure(text=textchange)           #輸入框顯示結果
        displayf.configure(text='')                 #清空顯示框
        equal_is = True

def show_is():                          #顯示框內容
    global textchange                   #宣告全域性變數
    if textchange != '':
        try:
            textshow = eval(textchange)
        except(SyntaxError, TypeError, NameError):
            displayf.configure(text='錯誤')           #出錯顯示
        else:
            displayf.configure(text=textshow)       #沒出錯顯示結果
    else:
        displayf.configure(text='')                 #輸入框為空就清空顯示框

#建立窗體
window = tk.Tk()
window.geometry('250x350')
window.title('簡易計算器')
#繫結鍵盤事件
window.bind('<Key>', bind_print)                    #當鍵盤按下任意鍵,執行bind_print

equal_is = False
txtchange=''        #設定輸入框的內容

#生成輸入框
printf=tk.Label(window, text='', bg='white', fg='black', font=('宋體',24), anchor='w', relief='flat')
printf.grid(column=0, row=0, columnspan=5, rowspan=1, sticky='we')
#生成顯示框
displayf=tk.Label(window, bg='white', fg='grey', height=1, font=('宋體',22), anchor='w', relief='flat')
displayf.grid(column=0, row=1, columnspan=5, rowspan=1, sticky='we')

#生成按鈕
button = {}
button['1'] = create_button('1', 0, 4, 1, 1)
button['2'] = create_button('2', 1, 4, 1, 1)
button['3'] = create_button('3', 2, 4, 1, 1)
button['4'] = create_button('4', 0, 3, 1, 1)
button['5'] = create_button('5', 1, 3, 1, 1)
button['6'] = create_button('6', 2, 3, 1, 1)
button['7'] = create_button('7', 0, 2, 1, 1)
button['8'] = create_button('8', 1, 2, 1, 1)
button['9'] = create_button('9', 2, 2, 1, 1)
button['0'] = create_button('0', 0, 5, 1, 1)

button['.'] = create_button('.', 1, 5, 1, 1)
button['='] = create_button('=', 4, 5, 1, 1)
button['+'] = create_button('+', 3, 3, 1, 1)
button['-'] = create_button('-', 3, 4, 1, 1)
button['*'] = create_button('×', 3, 5, 1, 1, print='*')
button['/'] = create_button('÷', 4, 4, 1, 1, print='/')
button['←'] = create_button('←', 4, 3, 1, 1)

button['C'] = create_button('C', 2, 5, 1, 1)
button['('] = create_button('(', 3, 2, 1, 1)
button[')'] = create_button(')', 4, 2, 1, 1)

grid_rowconfigure(2, 3, 4, 5)
grid_columnconfigure(0, 1, 2, 3, 4)

#進行事件迴圈
window.mainloop()

執行結果