前言
最近在学习Python GUI, 选择的是 python 自带的 tkinter,优点是简单、快捷,缺点是不够美观。学了两天,用40行代码写了个简单的计算器,供大家学习参考。
- 本代码为本人原创,转载请注明出处。
- 仅限论坛学习交流使用,请勿滥用,谢谢!
- 代码并未做全面测试,有问题请在评论区留言。
效果展示
源代码如下
from tkinter import *
window = Tk()
window.title('计算器')
window.attributes("-topmost", 1) # 窗口置顶
str1 = ''
def input(msg):
"""输入"""
global str1
str1 = str1 + msg
text(str1)
def text(msg):
"""输出"""
label_show.config(text=msg)
def clear():
"""清除"""
global str1
label_show.config(text='')
str1 = ''
def get_result():
"""计算"""
global str1
label_show.config(text=eval(str1))
str1 = str(eval(str1))
label_show = Label(window, bg='yellow', width=30, height=5)
label_show.grid(row=0, column=0, columnspan=4, pady=4)
Button(window, text='1', font=('黑体', 15), width=3, command=lambda: input('1')).grid(row=1, column=0, padx=4, pady=4)
Button(window, text='2', font=('黑体', 15), width=3, command=lambda: input('2')).grid(row=1, column=1, padx=4, pady=4)
Button(window, text='3', font=('黑体', 15), width=3, command=lambda: input('3')).grid(row=1, column=2, padx=4, pady=4)
Button(window, text='+', font=('黑体', 15), width=3, command=lambda: input('+')).grid(row=1, column=3, padx=4, pady=4)
Button(window, text='4', font=('黑体', 15), width=3, command=lambda: input('4')).grid(row=2, column=0, padx=4, pady=4)
Button(window, text='5', font=('黑体', 15), width=3, command=lambda: input('5')).grid(row=2, column=1, padx=4, pady=4)
Button(window, text='6', font=('黑体', 15), width=3, command=lambda: input('6')).grid(row=2, column=2, padx=4, pady=4)
Button(window, text='-', font=('黑体', 15), width=3, command=lambda: input('-')).grid(row=2, column=3, padx=4, pady=4)
Button(window, text='7', font=('黑体', 15), width=3, command=lambda: input('7')).grid(row=3, column=0, padx=4, pady=4)
Button(window, text='8', font=('黑体', 15), width=3, command=lambda: input('8')).grid(row=3, column=1, padx=4, pady=4)
Button(window, text='9', font=('黑体', 15), width=3, command=lambda: input('9')).grid(row=3, column=2, padx=4, pady=4)
Button(window, text='x', font=('黑体', 15), width=3, command=lambda: input('*')).grid(row=3, column=3, padx=4, pady=4)
Button(window, text='0', font=('黑体', 15), width=3, command=lambda: input('0')).grid(row=4, column=0, padx=4, pady=4)
Button(window, text='C', font=('黑体', 15), width=3, command=clear).grid(row=4, column=1, padx=4, pady=4)
Button(window, text='÷', font=('黑体', 15), width=3, command=lambda: input('/')).grid(row=4, column=2, padx=4, pady=4)
Button(window, text='=', font=('黑体', 15), width=3, command=get_result).grid(row=4, column=3, padx=4, pady=4)
window.mainloop()
利用 pyinstaller 打包成exe,大小8m
打包命令如下:
打包命令解释:打包成单个可执行文件,指定ico,不显示命令行窗口
pyinstaller -F -w --icon=D:\IDM下载\ico\jisuanqi.ico --onefile jisuanqi.py