首页 > 编程语言 >python练习-简单计算器

python练习-简单计算器

时间:2023-06-04 11:44:31浏览次数:39  
标签:bg get python button 练习 place entry input 计算器

#  *_* coding:utf8 *_*

# 简单计算器
import tkinter
from functools import partial


# 按钮输入调用
def get_input(entry1, argu):
# 从entry窗口展示中获取输入的内容
input_data = entry1.get()

# 合法运算符 : + - * / -- ** // +-
# ------------ 输入合法性判断的优化 ------------
# 最后一个字符不是纯数字(已经有算数符号),原窗口值不为空,且输入值为运算符
# if not input_data[-1:].isdecimal() and (not argu.isdecimal()):
# if input_data[-2:] in ["--", "**", "//", "+-"]:
# return
# if (input_data[-1:] + argu) not in ["--", "**", "//", "+-"]:
# return
# ------------------------------------------------

# 出现连续+,则第二个+为无效输入,不做任何处理
if (input_data[-1:] == '+') and (argu == '+'):
return
# 出现连续+--,则第三个-为无效输入,不做任何处理
if (input_data[-2:] == '+-') and (argu == '-'):
return
# 窗口已经有--后面字符不能为+或-
if (input_data[-2:] == '--') and (argu in ['-', '+']):
return
# 窗口已经有 ** 后面字符不能为 * 或 /
if (input_data[-2:] == '**') and (argu in ['*', '/']):
return

# 输入合法将字符插入到entry窗口结尾
entry1.insert("end", argu)


# 退格(撤销输入)
def backspace(entry1):
input_len = len(entry1.get())
# 删除entry窗口中最后的字符
entry1.delete(input_len - 1)


# 清空entry内容(清空窗口)
def clear(entry1):
entry1.delete(0, "end")


# 计算
def calc(entry1):
input_data = entry1.get()
# 计算前判断输入内容是否为空;首字符不能为*/;*/不能连续出现3次;
if not input_data:
return

clear(entry1)

# 异常捕获,在进行数据运算时如果出现异常进行相应处理
# noinspection PyBroadException
try:
# eval() 函数用来执行一个字符串表达式,并返回表达式的值;并将执行结果转换为字符串
output_data = str(eval(input_data))
except Exception:
# 将提示信息输出到窗口
entry1.insert("end", "Calculation error")
else:
# 将计算结果显示在窗口中
if len(output_data) > 20:
entry1.insert("end", "Value overflow")
else:
entry1.insert("end", output_data)


if __name__ == '__main__':
root = tkinter.Tk()
root.title("Yummy")

# 框体大小可调性,分别表示x,y方向的可变性;
root.resizable(0, 0)

button_bg = 'pink'
math_sign_bg = 'DarkTurquoise'
cal_output_bg = 'Yellow'
button_active_bg = 'gray'

# justify:显示多行文本的时候, 设置不同行之间的对齐方式,可选项包括LEFT, RIGHT, CENTER
# 文本从窗口左方开始显示,默认可以显示20个字符
# row:entry组件在网格中的横向位置
# column:entry组件在网格中的纵向位置
# columnspan:正常情况下,一个插件只占一个单元;可通过columnspan来合并一行中的多个相邻单元
entry = tkinter.Entry(root, justify="right", font=1)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)


def place_button(text, func, func_params, bg=button_bg, **place_params):
# 偏函数partial,可以理解为定义了一个模板,后续的按钮在模板基础上进行修改或添加特性
# activebackground:按钮按下后显示颜place_params色
my_button = partial(tkinter.Button, root, bg=button_bg, padx=10, pady=3, activebackground=button_active_bg)
button = my_button(text=text, bg=bg, command=lambda: func(*func_params))
button.grid(**place_params)


# 文本输入类按钮
place_button('7', get_input, (entry, '7'), row=1, column=0, ipadx=5, pady=5)
place_button('8', get_input, (entry, '8'), row=1, column=1, ipadx=5, pady=5)
place_button('9', get_input, (entry, '9'), row=1, column=2, ipadx=5, pady=5)
place_button('4', get_input, (entry, '4'), row=2, column=0, ipadx=5, pady=5)
place_button('5', get_input, (entry, '5'), row=2, column=1, ipadx=5, pady=5)
place_button('6', get_input, (entry, '6'), row=2, column=2, ipadx=5, pady=5)
place_button('1', get_input, (entry, '1'), row=3, column=0, ipadx=5, pady=5)
place_button('2', get_input, (entry, '2'), row=3, column=1, ipadx=5, pady=5)
place_button('3', get_input, (entry, '3'), row=3, column=2, ipadx=5, pady=5)
place_button('0', get_input, (entry, '0'), row=4, column=0, padx=8, pady=5,
columnspan=2, sticky=tkinter.E + tkinter.W + tkinter.N + tkinter.S)
place_button('.', get_input, (entry, '.'), row=4, column=2, ipadx=7, padx=5, pady=5)

# 运算输入类按钮(只是背景色不同)
# 字符大小('+','-'宽度不一样,使用ipadx进行修正)
place_button('+', get_input, (entry, '+'), bg=math_sign_bg, row=1, column=3, ipadx=5, pady=5)
place_button('-', get_input, (entry, '-'), bg=math_sign_bg, row=2, column=3, ipadx=5, pady=5)
place_button('*', get_input, (entry, '*'), bg=math_sign_bg, row=3, column=3, ipadx=5, pady=5)
place_button('/', get_input, (entry, '/'), bg=math_sign_bg, row=4, column=3, ipadx=5, pady=5)

# 功能输入类按钮(背景色、触发功能不同)
place_button('<-', backspace, (entry,), row=5, column=0, ipadx=5, padx=5, pady=5)
place_button('C', clear, (entry,), row=5, column=1, pady=5, ipadx=5)
place_button('=', calc, (entry,), bg=cal_output_bg, row=5, column=2, ipadx=5, padx=5, pady=5,
columnspan=2, sticky=tkinter.E + tkinter.W + tkinter.N + tkinter.S)

root.mainloop()

标签:bg,get,python,button,练习,place,entry,input,计算器
From: https://www.cnblogs.com/ashuai123/p/17455423.html

相关文章

  • Python中解包与打包 */**
    解包打包本质:解包的逆向操作打包是将多个值组合成一个可迭代对象的过程。常见的打包方式是使用元组或列表或字典。打包操作使用=符号进行赋值,将多个值组合成一个可迭代对象。......
  • 为teamcity的代码语法检查工具pyflakes增加支持python2和python3
    TeamCity和pyflakesTeamCity是一款由JetBrains公司开发的持续集成和部署工具,它提供了丰富的功能来帮助团队协作进行软件开发。其中包括代码检查、自动化构建、测试运行、版本控制等多个方面。在我们团队中使用TeamCity进行配合pyflakes代码检查,我们需要升级pyflakes到支持python......
  • python——pandas数据分析(表格处理)工具实现Apriori算法
    pandas是基于NumPy的一种工具,名字很卡哇伊,来源是由“Paneldata”(面板数据,一个计量经济学名词)两个单词拼成的。pandas纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。主要应用于处理大型数据集。数据处理速度算是最大的特色,剩下的就是个python版的exc......
  • 【python基础】复杂数据类型-列表类型(列表切片)
    1.列表切片前面学习的是如何处理列表的所有数据元素。python还可以处理列表的部分元素,python称之为切片。1.1创建切片创建切片,可指定要使用的第一个数据元素的索引和最后一个数据元素的索引。与range函数一样,python在到达指定的第二个索引前面的数据元素后停止。比如要输出列表......
  • Redis(二) -- 练习
    模拟手机验证码需求:使用redis模拟手机验证码发送,验证码有效期60s,验证验证码输入不能超过3次,超过3次今天就没机会了//验证手机号/***判断字符串是否符合手机号码格式*移动号段:134135136137138139147148150151152157158159165172178182183184187......
  • Python可视化模块
    Python可视化模块一个简单的python包就能够实现数据的可视化功能,这个第三方动态可视化的数据模块就是Pynimate效果是这样的安装pipinstallpynimate使用指南想要使用Pynimate,直接import一下就行importpynimateasnim输入数据后,Pynimate将使用函数Barplot()......
  • 【python】函数print
    f-string python中的字符串通常被括在双引号("")或单引号('')内。要创建f-string,你只需要在字符串的开头引号前添加一个 f 或 F。例如,"This" 是一个字符串,而 f"This" 是一个f-string。当使用f-string来显示变量时,你只需要在一组大括号 {} 内指定变量的名字。而在运行时......
  • 微积分续期末练习
    期末练习DA解:\(f(x)=\frac{x-x^3}{\sin\pix}\),则\(f(x)\)的定义域为\(\mathbb{R}-\mathbb{Z}\),因此\(x\in0,\pm1,\pm2,\cdots\)都是\(f(x)\)的间断点,其中\(x=0\)为可去间断点,因为\[\lim\limits_{x\to0}\frac{x-x^3}{\sin\pix}=\lim\limits_{x\to0......
  • Reinforcement Learning之Q-Learning - Python实现
    算法特征①.以真实reward训练Q-function;②.从最大Q方向更新policy\(\pi\)算法推导PartⅠ:RL之原理整体交互流程如下,定义策略函数(policy)\(\pi\),输入为状态(state)\(s\),输出为动作(action)\(a\),则,\[\begin{equation*}a=\pi(s)\end{equation*}\]令......
  • 【Python】如何在FastAPI中使用UUID标记日志,以跟踪一个请求的完整生命周期
    为什么要使用uuid标记日志?在分布式系统中,一个请求可能会经过多个服务,每个服务都会生成自己的日志。如果我们只使用普通的日志记录,那么很难将这些日志串联在一起,以至难以跟踪一个请求的完整生命周期。如果能够使用uuid标记日志,为每个请求生成一个唯一的uuid,且这个日志可以在不同......