日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python實現簡單的計算器功能_python

作者:分不清是月光還是路燈 ? 更新時間: 2022-09-15 編程語言

本文實例為大家分享了python實現簡單計算器的具體代碼,供大家參考,具體內容如下

今天學習到python中界面設計部分,常用的幾種圖形化界面庫有:Jython、wxPython和tkinter。

主要介紹tkinter模塊,tkinter模塊(tk接口)是Python的標準tk GUI工具包的接口。tk和tkinter可以在大多數的UNIX平臺下使用,同樣可以應用在Windows和Macintosh系統里。Tk8.0的后續版本可以實現本地窗口風格,并良好地運行在絕大多數平臺中。

下面使用tkinter設計完成計算器功能。

(1)首先呈現一下計算器初始界面:

(2)簡單說明:已經實現計算器的基本功能

(3)主要代碼說明:

①導入包

import tkinter
from tkinter import *
import re
import tkinter.messagebox

?②界面布局設置

# 創建主窗口
root = Tk()
# 設置窗口大小和位置
root.title("---計算器---")
root.geometry("320x210+500+200")
# 自動刷新字符串變量,可用 set 和 get 方法進行傳值和取值
contentVar = tkinter.StringVar(root,'')
# 創建單行文本框
contentEntry = tkinter.Entry(root, textvariable=contentVar)
# 設置文本框坐標及寬高
contentEntry.place(x=20, y=10, width=260, height=30)
?
# 按鈕顯示內容
bvalue = ['CLC', '+', '-', '//', '0', '1', '2', '√', '3', '4', '5', '*', '6', '7', '8', '.', '9', '/', '**', '=']
index = 0
# 將按鈕進行 5x4 放置
for row in range(5):
? ? for col in range(4):
? ? ? ? d = bvalue[index]
? ? ? ? index += 1
? ? ? ? btnDigit = tkinter.Button(root, text=d, command=lambda x=d:onclick(x))
? ? ? ? btnDigit.place(x=20 + col * 70, y=50 + row * 30, width=50, height=20)
root.mainloop()

③按鈕事件的響應函數(可在評論區進行交流)

# 點擊事件
def onclick(btn):
? ? # 運算符
? ? operation = ('+', '-', '*', '/', '**', '//')
? ? # 獲取文本框中的內容
? ? content = contentVar.get()
? ? # 如果已有內容是以小數點開頭的,在前面加 0
? ? if content.startswith('.'):
? ? ? ? content = '0' + content ?# 字符串可以直接用+來增加字符
? ? # 根據不同的按鈕作出不同的反應
? ? if btn in '0123456789':
? ? ? ? # 按下 0-9 在 content 中追加
? ? ? ? content += btn
? ? elif btn == '.':
? ? ? ? # 將 content 從 +-*/ 這些字符的地方分割開來
? ? ? ? lastPart = re.split(r'\+|-|\*|/', content)[-1]
? ? ? ? if '.' in lastPart:
? ? ? ? ? ? # 信息提示對話框
? ? ? ? ? ? tkinter.messagebox.showerror('錯誤', '重復出現的小數點')
? ? ? ? ? ? return
? ? ? ? else:
? ? ? ? ? ? content += btn
? ? elif btn == 'CLC':
? ? ? ? # 清除文本框
? ? ? ? content = ''
? ? elif btn == '=':
? ? ? ? try:
? ? ? ? ? ? # 對輸入的表達式求值
? ? ? ? ? ? content = str(eval(content))
? ? ? ? except:
? ? ? ? ? ? tkinter.messagebox.showerror('錯誤', '表達式有誤')
? ? ? ? ? ? return
? ? elif btn in operation:
? ? ? ? if content.endswith(operation):
? ? ? ? ? ? tkinter.messagebox.showerror('錯誤', '不允許存在連續運算符')
? ? ? ? ? ? return
? ? ? ? content += btn
? ? elif btn == '√':
? ? ? ? # 從 . 處分割存入 n,n 是一個列表
? ? ? ? n = content.split('.')
? ? ? ? # 如果列表中所有的都是數字,就是為了檢查表達式是不是正確的
? ? ? ? if all(map(lambda x: x.isdigit(), n)):
? ? ? ? ? ? content = eval(content) ** 0.5
? ? ? ? else:
? ? ? ? ? ? tkinter.messagebox.showerror('錯誤', '表達式錯誤')
? ? ? ? ? ? return

原文鏈接:https://blog.csdn.net/m0_51666362/article/details/121797908

欄目分類
最近更新