Vuetify — Button Groups

Vuetify is a popular UI framework for Vue apps.

In this article, we’ll look at how to work with the Vuetify framework.

Button Groups

The v-btn-toggle component is a wrapper for v-item-group that works with v-btn components.

We can use it to add a group of buttons that can be toggled.

For example, we can write:

<template>
  <v-container class="grey lighten-5">
    <v-row>
      <v-col>
        <v-card flat class="py-12">
          <v-card-text>
            <v-row align="center" justify="center">
              <v-btn-toggle v-model="toggle" rounded>
                <v-btn>
                  <v-icon>mdi-format-align-left</v-icon>
                </v-btn>
                <v-btn>
                  <v-icon>mdi-format-align-center</v-icon>
                </v-btn>
                <v-btn>
                  <v-icon>mdi-format-align-right</v-icon>
                </v-btn>
                <v-btn>

#javascript #web-development #programming

What is GEEK

Buddha Community

Vuetify — Button Groups

Flutter Custom Widget to Make A Group Buttons

Flutter widget to create a group of buttons fast 🚀

Included Radio and CheckBox buttons models with custom groping types 🤤
Show some ❤️ and star the repo to support the project!

GroupButtonControllerGroupButtonBuilderGroupButtonOptions

Getting Started

Follow these steps to use this package

Add dependency

dependencies:
  group_button: ^5.2.2

Add import package

import 'package:group_button/group_button.dart';

Easy to use

Simple example of use GroupButton
Put this code in your project at an screen and learn how it works 😊

GroupButton(
    isRadio: false,
    onSelected: (index, isSelected) => print('$index button is selected'),
    buttons: ["12:00", "13:00", "14:30", "18:00", "19:00", "21:40"],
)

Controller

Starting from version 4.1.0
You can control your Group Button using the controller

final controller = GroupButtonController();

Column(
  children: [
    GroupButton.checkbox(
      controller: controller,
      buttons: ['12:00', '13:00', '14:00'],
      onSelected: (i, selected) => debugPrint('Button #$i $selected'),
    ),
    TextButton(
      onPressed: () => controller.selectIndex(1),
      child: const Text('Select 1 button'),
    )
  ],
),

Generic button value

In new 5.0.0 version you can set custom buttons value type
It can be int, DateTime, double or YourCustomClass
Button text will be result of .toString() model method in common button display case
 

GroupButton<DateTime>(
  buttons: [DateTime(2022, 4, 9), DateTime(2022, 4, 10)],
)

Also you can use generic button values with cutsom buttonBuilder
In order to turn values into any widget

GroupButton<DateTime>(
  buttons: [DateTime(2022, 4, 9), DateTime(2022, 4, 10)],
  buttonBuilder: (selected, date, context) {
    return Text('${date.year}-${date.month}-${date.day}');
  },
),

Customize

In order to customize your buttons inside GroupButton you can use GroupButtonOptions

GroupButtonOptions(
  selectedShadow: const [],
  selectedTextStyle: TextStyle(
    fontSize: 20,
    color: Colors.pink[900],
  ),
  selectedColor: Colors.pink[100],
  unselectedShadow: const [],
  unselectedColor: Colors.amber[100],
  unselectedTextStyle: TextStyle(
    fontSize: 20,
    color: Colors.amber[900],
  ),
  selectedBorderColor: Colors.pink[900],
  unselectedBorderColor: Colors.amber[900],
  borderRadius: BorderRadius.circular(100),
  spacing: 10,
  runSpacing: 10,
  groupingType: GroupingType.wrap,
  direction: Axis.horizontal,
  buttonHeight: 60,
  buttonWidth: 60,
  mainGroupAlignment: MainGroupAlignment.start,
  crossGroupAlignment: CrossGroupAlignment.start,
  groupRunAlignment: GroupRunAlignment.start,
  textAlign: TextAlign.center,
  textPadding: EdgeInsets.zero,
  alignment: Alignment.center,
  elevation: 0,
),

Examples

You can check more examples of using this package here


 

Thanks to all contributors of this package


 

For help getting started with 😍 Flutter, view online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add group_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  group_button: ^5.2.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:group_button/group_button.dart';

example/lib/main.dart

import 'package:example/examples/common_example/example.dart';
import 'package:flutter/material.dart';
import 'routes.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GroupButton Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      routes: Routes.appRoutes,
      home: CommonExample(),
    );
  }
}

Download Details:

Author: frezycode.com

Source Code: https://github.com/Frezyx/group_button

#flutter #widget #button #group #radio #checkbox 

Upload, Preview & Download Images using JavaScript & PHP

In this guide, you’ll learn how to Upload, Preview & Download Images using JavaScript & PHP.

To create Upload, Preview & Download Images using JavaScript & PHP. First, you need to create two Files one PHP File and another one is CSS File.

1: First, create a PHP file with the name of index.php

 

<?php
//if download button clicked
if(isset($_POST['downloadBtn'])){
    //getting the user img url from input field
    $imgURL = $_POST['file']; //storing in variable
    $regPattern = '/\.(jpe?g|png|gif|bmp)$/i'; //pattern to validataing img extension
    if(preg_match($regPattern, $imgURL)){ //if pattern matched to user img url
        $initCURL = curl_init($imgURL); //intializing curl
        curl_setopt($initCURL, CURLOPT_RETURNTRANSFER, true);
        $downloadImgLink = curl_exec($initCURL); //executing curl
        curl_close($initCURL); //closing curl
        // now we convert the base 64 format to jpg to download
        header('Content-type: image/jpg'); //in which extension you want to save img
        header('Content-Disposition: attachment;filename="image.jpg"'); //in which name you want to save img
        echo $downloadImgLink;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Download in PHP | Codequs</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <div class="preview-box">
            <div class="cancel-icon"><i class="fas fa-times"></i></div>
            <div class="img-preview"></div>
            <div class="content">
                <div class="img-icon"><i class="far fa-image"></i></div>
                <div class="text">Paste the image url below, <br/>to see a preview or download!</div>
            </div>
        </div>
        <form action="index.php" method="POST" class="input-data">
            <input id="field" type="text" name="file" placeholder="Paste the image url to download..." autocomplete="off">
            <input id="button" name="downloadBtn" type="submit" value="Download">
        </form>
    </div>
    <script>
        $(document).ready(function(){
            //if user focus out from the input field
            $("#field").on("focusout", function(){
                //getting user entered img URL
                var imgURL = $("#field").val();
                if(imgURL != ""){ //if input field isn't blank
                    var regPattern = /\.(jpe?g|png|gif|bmp)$/i; //pattern to validataing img extension
                    if(regPattern.test(imgURL)){ //if pattern matched to image url
                        var imgTag = '<img src="'+ imgURL +'" alt="">'; //creating a new img tag to show img
                        $(".img-preview").append(imgTag); //appending img tag with user entered img url
                        // adding new class which i've created in css
                        $(".preview-box").addClass("imgActive");
                        $("#button").addClass("active");
                        $("#field").addClass("disabled");
                        $(".cancel-icon").on("click", function(){
                            //we'll remove all new added class on cancel icon click
                            $(".preview-box").removeClass("imgActive");
                            $("#button").removeClass("active");
                            $("#field").removeClass("disabled");
                            $(".img-preview img").remove();
                            // that's all in javascript/jquery now the main part is PHP
                        });
                    }else{
                        alert("Invalid img URL - " + imgURL);
                        $("#field").val('');//if pattern not matched we'll leave the input field blank
                    }
                }
            });
        });
    </script>
    
</body>
</html>

 

2: Second, create a CSS file with the name of style.css

 

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}
html,body{
    display: grid;
    height: 100%;
    place-items: center;
}
::selection{
   color: #fff;
   background: #4158d0;    
}
.wrapper{
    height: 450px;
    width: 500px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-direction: column;
}
.wrapper .preview-box{
    position: relative;
    width: 100%;
    height: 320px;
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    border: 2px dashed #c2cdda;
}
.preview-box.imgActive{
    border: 2px solid transparent;
}
.preview-box .cancel-icon{
    position: absolute;
    right: 20px;
    top: 10px;
    z-index: 999;
    color: #4158d0;
    font-size: 20px;
    cursor: pointer;
    display: none;
}
.preview-box.imgActive:hover .cancel-icon{
    display: block;
}
.preview-box .cancel-icon:hover{
    color: #ff0000;
}
.preview-box .img-preview{
    height: 100%;
    width: 100%;
    position: absolute;
}
.preview-box .img-preview img{
    height: 100%;
    width: 100%;
    border-radius: 5px;
}
.wrapper .preview-box .img-icon{
    font-size: 100px;
    background: linear-gradient(-135deg, #c850c0, #4158d0);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
.wrapper .preview-box .text{
    font-size: 18px;
    font-weight: 500;
    color: #5B5B7B;
}
.wrapper .input-data{
    height: 130px;
    width: 100%;;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    flex-direction: column;
}
.wrapper .input-data #field{
    width: 100%;
    height: 50px;
    outline: none;
    font-size: 17px;
    padding: 0 15px;
    user-select: auto;
    border-radius: 5px;
    border: 2px solid lightgrey;
    transition: all 0.3s ease;
}
.input-data #field.disabled{
    color: #b3b3b3;
    pointer-events: none;
}
.wrapper .input-data #field:focus{
    border-color: #4158d0;
}
.input-data #field::placeholder{
    color: #b3b3b3;
}
.wrapper .input-data #button{
    height: 50px;
    width: 100%;
    border: none;
    outline: none;
    color: #fff;
    font-weight: 500;
    font-size: 18px;
    cursor: pointer;
    border-radius: 5px;
    opacity: 0.5;
    pointer-events: none;
    background: linear-gradient(-135deg, #c850c0, #4158d0);
    transition: all 0.3s ease;
}
.input-data #button.active{
    opacity: 1;
    pointer-events: auto;
}
.input-data #button:active{
    transform: scale(0.99);
}

Now you’ve successfully created a How to Upload, Preview & Download Image using JavaScript & PHP.

米 萱萱

米 萱萱

1678577880

3 种不同的 Python 计算机编程方法

在本文中,我们将学习 3 种不同的 Python 计算机编程技术。您是否正在寻找功能强大且易于使用的 Python 计算器程序? 

该计算器执行算术运算以及方程求解、指数运算和三角函数。

但是,如果我们告诉您可以用 Python 编写自己的计算机程序呢?

如果您熟悉 Python 编程的基础知识,我们将向您展示如何从头开始创建允许您执行基本算术运算的图形用户界面。 
所以,事不宜迟,让我们开始吧。

方法-1:一个简单的Python计算器程序

# Basic Calculations# Calculator Program in Python by using input() and format() functions
#Promting input from the user
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))
#addition
print("{} + {} = ".format(n1, n2))print(n1 + n2)
#subtraction
print("{} - {} = ".format(n1, n2))print(n1 - n2)
#multiplication
print("{} * {} = ".format(n1, n2))print(n1 * n2)
#division
print("{} / {} = ".format(n1, n2))print(n1 / n2)
Copy code

出口

说明: 在上面的程序中,我们取两个数值(这里使用浮点数据类型),得到输入两个数后的所有输出(加减乘除)。

方法 2:Python 计算机程序使用 .

#Calculator Program in python by defining operations
# Define Operators or Functions: Addition, Subtraction, Multiplication, and Division
# Addition
def addition(n1, n2):    return n1 + n2
# Subtraction
def subtraction(n1, n2):    return n1 - n2
# Multiplication
def multiplication(n1, n2):    return n1 * n2
# Division
def division(n1, n2):    return n1 / n2

print("Select Operations")print(    "1. Addition\n"\    "2. Subtraction\n"\    "3. Multiplication\n"\    "4. Division\n")
# Giving the option to the user to choose the operation
operation = int(input("Enter choice of operation 1/2/3/4: "))

#Taking Input from the Users
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))

# Apply Conditional Statements: To make operation as-per-user choices
if operation == 1:    print (n1, "+", n2, "=", addition(n1, n2))
elif operation == 2:    print (n1, "-", n2, "=", subtraction(n1, n2)) 
elif operation == 3:    print (n1, "*", n2, "=", multiplication(n1, n2))     elif operation == 4:    print (n1, "/", n2, "=", division(n1, n2))     else:    print("Invalid Input")
Copy code

出口

解释:

上面的程序分三步创建:

步骤-1:  定义函数:加减乘除

第 2 步:  吸引用户

(我)。选择要采取的行动

(ii). 输入第一个和第二个数字(浮点数据类型)

第 3 步:   应用条件语句:根据用户的操作做出选择

方法三:在Python中使用tkinter创建一个GUI计算器。

#importing tkinter libraryimport tkinter as tkimport tkinter.messageboxfrom tkinter.constants import SUNKEN
window=tk.Tk()window.title('My Calci')frame=tk.Frame(master=window,bg="skyblue",padx=10)frame.pack()entry=tk.Entry(master=frame,relief=SUNKEN,borderwidth=3,width=30)entry.grid(row=0,column=0,columnspan=4,ipady=2,pady=2)
#define myclick function to get the input from the user
def myclick(number):    entry.insert(tk.END,number)
#define an equal function to evaluate the value# try-except is use to handle the error
def equal():    try:        y=str(eval(entry.get()))        entry.delete(0,tk.END)        entry.insert(0,y)    except:        tkinter.messagebox.showinfo("Error","Syntax Error")
#define clear function to delete the previous inputs
def clear():    entry.delete(0,tk.END)
# Buttons for the First Row# 9, 8, 7, +
button_1=tk.Button(master=frame,text='9',padx=15,pady=5,width=3,command=lambda:myclick(9))button_1.grid(row=1,column=0,pady=2)
button_2=tk.Button(master=frame,text='8',padx=15,pady=5,width=3,command=lambda:myclick(8))button_2.grid(row=1,column=1,pady=2)
button_3=tk.Button(master=frame,text='7',padx=15,pady=5,width=3,command=lambda:myclick(7))button_3.grid(row=1,column=2,pady=2)
#addition button (+)button_add=tk.Button(master=frame,text="+",padx=15,pady=5,width=3,command=lambda:myclick('+'))button_add.grid(row=1,column=3,pady=2)

#buttons for the second row# 6, 5, 4, -
button_4=tk.Button(master=frame,text='6',padx=15,pady=5,width=3,command=lambda:myclick(6))button_4.grid(row=2,column=0,pady=2)
button_5=tk.Button(master=frame,text='5',padx=15,pady=5,width=3,command=lambda:myclick(5))button_5.grid(row=2,column=1,pady=2)
button_6=tk.Button(master=frame,text='4',padx=15,pady=5,width=3,command=lambda:myclick(4))button_6.grid(row=2,column=2,pady=2)
#subtraction button (-)button_subtract=tk.Button(master=frame,text="-",padx=15,pady=5,width=3,command=lambda:myclick('-'))button_subtract.grid(row=2,column=3,pady=2)

#buttons for the third row# 3, 2, 1, and *
button_7=tk.Button(master=frame,text='3',padx=15,pady=5,width=3,command=lambda:myclick(3))button_7.grid(row=3,column=0,pady=2)
button_8=tk.Button(master=frame,text='2',padx=15,pady=5,width=3,command=lambda:myclick(2))button_8.grid(row=3,column=1,pady=2)
button_9=tk.Button(master=frame,text='1',padx=15,pady=5,width=3,command=lambda:myclick(1))button_9.grid(row=3,column=2,pady=2)
#multiply button (*)button_multiply=tk.Button(master=frame,text="*",padx=15,pady=5,width=3,command=lambda:myclick('*'))button_multiply.grid(row=3,column=3,pady=2)

#buttons for the fourth row# clear, 0, equal, and /
#clear buttonbutton_clear=tk.Button(master=frame,text="C",padx=15,pady=5,width=3,command=clear)button_clear.grid(row=4,column=0,pady=2)
# 0 buttonbutton_0=tk.Button(master=frame,text='0',padx=15,pady=5,width=3,command=lambda:myclick(0))button_0.grid(row=4,column=1,pady=2)
#equal buttonbutton_equal=tk.Button(master=frame,text="=",padx=15,pady=5,width=3,command=equal)button_equal.grid(row=4,column=2,pady=2)
#division button (/)button_div=tk.Button(master=frame,text="/",padx=15,pady=5,width=3,command=lambda:myclick('/'))button_div.grid(row=4,column=3,pady=2)

window.mainloop()
Copy code

出口

您现在可以在这里执行任何算术运算,如果输入错误,将导致语法错误,如下所示:

解释

GUI 或图形用户界面是与计算机交互的交互式(视觉)方式。您可以单击以输入您的值并获得结果。在上述方法中,我们使用标准的 Python GUI 库,即 tkinter,它允许用户创建快速且易于使用的 GUI 应用程序。

在上面的程序中,我们首先导入了Python的tkinter库;第二,我们框定窗口(即窗口标题、大小、背景颜色等)
。第三,我们定义三个函数:myclick、equal 和 clear 分别用于插入值、输入值和删除值。最后,我们创建四行四列的按钮。

结论

简而言之,Python 计算器程序对于任何使用数字或数据的人来说都是一个非常强大的工具。无论您是学生、研究人员还是专业人士,我们的软件都可以帮助您节省时间、提高准确性并简化您的工作流程。在本文中,我们讨论了用 Python 创建计算机程序的三种不同方法。

文章原文来源: https: //www.naukri.com

#python 

Hoang  Kim

Hoang Kim

1678500060

3 phương pháp khác nhau để lập trình máy tính trong Python

Trong bài viết này, chúng ta sẽ tìm hiểu về 3 phương pháp khác nhau để lập trình máy tính trong python. Bạn đang tìm kiếm một chương trình máy tính Python mạnh mẽ và dễ sử dụng? 

Máy tính thực hiện các phép toán số học cùng với việc giải các phương trình, phép toán hàm mũ và lượng giác.

Nhưng nếu chúng tôi nói với bạn rằng bạn có thể tự tạo một chương trình máy tính bằng Python thì sao?

Nếu bạn biết lập trình Python cơ bản, chúng tôi sẽ chỉ cho bạn cách tạo giao diện người dùng đồ họa từ đầu để có thể thực hiện các phép tính số học cơ bản. 
Vì vậy, không có gì khó chịu, hãy bắt đầu.

Phương pháp -1: Chương trình máy tính đơn giản trong Python

# Basic Calculations# Calculator Program in Python by using input() and format() functions
#Promting input from the user
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))
#addition
print("{} + {} = ".format(n1, n2))print(n1 + n2)
#subtraction
print("{} - {} = ".format(n1, n2))print(n1 - n2)
#multiplication
print("{} * {} = ".format(n1, n2))print(n1 * n2)
#division
print("{} / {} = ".format(n1, n2))print(n1 / n2)
Copy code

Lối ra

Giải thích:  Trong chương trình trên, chúng tôi lấy hai giá trị số (ở đây chúng tôi đang sử dụng kiểu dữ liệu float) và nhận tất cả các kết quả đầu ra (cộng, trừ, nhân và chia) sau khi chúng tôi nhập hai số.

Cách 2: Chương trình máy tính Python sử dụng hàm

#Calculator Program in python by defining operations
# Define Operators or Functions: Addition, Subtraction, Multiplication, and Division
# Addition
def addition(n1, n2):    return n1 + n2
# Subtraction
def subtraction(n1, n2):    return n1 - n2
# Multiplication
def multiplication(n1, n2):    return n1 * n2
# Division
def division(n1, n2):    return n1 / n2

print("Select Operations")print(    "1. Addition\n"\    "2. Subtraction\n"\    "3. Multiplication\n"\    "4. Division\n")
# Giving the option to the user to choose the operation
operation = int(input("Enter choice of operation 1/2/3/4: "))

#Taking Input from the Users
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))

# Apply Conditional Statements: To make operation as-per-user choices
if operation == 1:    print (n1, "+", n2, "=", addition(n1, n2))
elif operation == 2:    print (n1, "-", n2, "=", subtraction(n1, n2)) 
elif operation == 3:    print (n1, "*", n2, "=", multiplication(n1, n2))     elif operation == 4:    print (n1, "/", n2, "=", division(n1, n2))     else:    print("Invalid Input")
Copy code

Lối ra

Giải trình:

Chương trình trên được tạo theo ba bước:

Bước -1:  Xác định Hàm: Cộng, Trừ, Nhân và Chia

Bước 2:  Thúc đẩy đầu vào của người dùng

(TÔI). Lựa chọn thao tác nào để thực hiện

(ii). Nhập số thứ nhất và số thứ hai (kiểu dữ liệu float)

Bước 3:   Áp dụng câu lệnh điều kiện: để đưa ra lựa chọn theo thao tác của người dùng

Phương pháp 3: Tạo máy tính GUI bằng tkinter trong Python

#importing tkinter libraryimport tkinter as tkimport tkinter.messageboxfrom tkinter.constants import SUNKEN
window=tk.Tk()window.title('My Calci')frame=tk.Frame(master=window,bg="skyblue",padx=10)frame.pack()entry=tk.Entry(master=frame,relief=SUNKEN,borderwidth=3,width=30)entry.grid(row=0,column=0,columnspan=4,ipady=2,pady=2)
#define myclick function to get the input from the user
def myclick(number):    entry.insert(tk.END,number)
#define an equal function to evaluate the value# try-except is use to handle the error
def equal():    try:        y=str(eval(entry.get()))        entry.delete(0,tk.END)        entry.insert(0,y)    except:        tkinter.messagebox.showinfo("Error","Syntax Error")
#define clear function to delete the previous inputs
def clear():    entry.delete(0,tk.END)
# Buttons for the First Row# 9, 8, 7, +
button_1=tk.Button(master=frame,text='9',padx=15,pady=5,width=3,command=lambda:myclick(9))button_1.grid(row=1,column=0,pady=2)
button_2=tk.Button(master=frame,text='8',padx=15,pady=5,width=3,command=lambda:myclick(8))button_2.grid(row=1,column=1,pady=2)
button_3=tk.Button(master=frame,text='7',padx=15,pady=5,width=3,command=lambda:myclick(7))button_3.grid(row=1,column=2,pady=2)
#addition button (+)button_add=tk.Button(master=frame,text="+",padx=15,pady=5,width=3,command=lambda:myclick('+'))button_add.grid(row=1,column=3,pady=2)

#buttons for the second row# 6, 5, 4, -
button_4=tk.Button(master=frame,text='6',padx=15,pady=5,width=3,command=lambda:myclick(6))button_4.grid(row=2,column=0,pady=2)
button_5=tk.Button(master=frame,text='5',padx=15,pady=5,width=3,command=lambda:myclick(5))button_5.grid(row=2,column=1,pady=2)
button_6=tk.Button(master=frame,text='4',padx=15,pady=5,width=3,command=lambda:myclick(4))button_6.grid(row=2,column=2,pady=2)
#subtraction button (-)button_subtract=tk.Button(master=frame,text="-",padx=15,pady=5,width=3,command=lambda:myclick('-'))button_subtract.grid(row=2,column=3,pady=2)

#buttons for the third row# 3, 2, 1, and *
button_7=tk.Button(master=frame,text='3',padx=15,pady=5,width=3,command=lambda:myclick(3))button_7.grid(row=3,column=0,pady=2)
button_8=tk.Button(master=frame,text='2',padx=15,pady=5,width=3,command=lambda:myclick(2))button_8.grid(row=3,column=1,pady=2)
button_9=tk.Button(master=frame,text='1',padx=15,pady=5,width=3,command=lambda:myclick(1))button_9.grid(row=3,column=2,pady=2)
#multiply button (*)button_multiply=tk.Button(master=frame,text="*",padx=15,pady=5,width=3,command=lambda:myclick('*'))button_multiply.grid(row=3,column=3,pady=2)

#buttons for the fourth row# clear, 0, equal, and /
#clear buttonbutton_clear=tk.Button(master=frame,text="C",padx=15,pady=5,width=3,command=clear)button_clear.grid(row=4,column=0,pady=2)
# 0 buttonbutton_0=tk.Button(master=frame,text='0',padx=15,pady=5,width=3,command=lambda:myclick(0))button_0.grid(row=4,column=1,pady=2)
#equal buttonbutton_equal=tk.Button(master=frame,text="=",padx=15,pady=5,width=3,command=equal)button_equal.grid(row=4,column=2,pady=2)
#division button (/)button_div=tk.Button(master=frame,text="/",padx=15,pady=5,width=3,command=lambda:myclick('/'))button_div.grid(row=4,column=3,pady=2)

window.mainloop()
Copy code

Lối ra

Bây giờ, bạn có thể thực hiện bất kỳ phép toán số học nào tại đây và nó sẽ báo lỗi cú pháp nếu bạn nhập sai Đầu vào, chẳng hạn như:

Giải trình

GUI hoặc giao diện người dùng đồ họa là một cách tương tác (trực quan) để tương tác với máy tính. Bạn có thể nhấp để nhập các giá trị của mình và nhận đầu ra. Trong phương pháp trên, chúng tôi sử dụng thư viện GUI tiêu chuẩn của Python, tức là tkinter, cho phép người dùng tạo các ứng dụng GUI nhanh và dễ sử dụng.

Trong Chương trình trên, trước tiên chúng ta nhập thư viện Python tkinter; thứ hai, chúng tôi tạo khung cho cửa sổ (tức là tiêu đề của cửa sổ, kích thước, màu nền, v.v.)
thứ ba, chúng tôi xác định ba chức năng: myclick, bằng và rõ ràng để chèn giá trị, đánh giá giá trị và xóa giá trị, tương ứng. Cuối cùng, chúng tôi tạo các nút trong bốn hàng và bốn cột.

Phần kết luận

Tóm lại, chương trình máy tính Python có thể là một công cụ cực kỳ mạnh mẽ cho bất kỳ ai làm việc với các con số hoặc dữ liệu. Cho dù bạn là sinh viên, nhà nghiên cứu hay chuyên gia, chương trình máy tính của chúng tôi có thể giúp bạn tiết kiệm thời gian, tăng độ chính xác và hợp lý hóa quy trình làm việc của bạn. Trong bài viết, chúng tôi đã thảo luận về ba phương pháp khác nhau để tạo chương trình máy tính bằng Python.

Nguồn bài viết gốc tại: https://www.naukri.com

#python 

3 Different Methods for Calculator Program in Python

In this article, we will learn about 3 different methods for computer programming in python. Looking for a powerful and user-friendly calculator program in Python? 

A calculator performs arithmetic operations along with solving equations, exponential and trigonometric operations.

But what if we told you that you can create a calculator program in Python yourself!

If you know basic Python programming, we will show you to create a graphical user interface from scratch that can perform basic arithmetic operations. 
So, without further delay, let’s get started.

Method -1: Simple Calculator Program in Python

# Basic Calculations# Calculator Program in Python by using input() and format() functions
#Promting input from the user
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))
#addition
print("{} + {} = ".format(n1, n2))print(n1 + n2)
#subtraction
print("{} - {} = ".format(n1, n2))print(n1 - n2)
#multiplication
print("{} * {} = ".format(n1, n2))print(n1 * n2)
#division
print("{} / {} = ".format(n1, n2))print(n1 / n2)
Copy code

Output

Explanation: In the above Program, we take two numeric values (here, we are taking float data type), and we get all the outputs (addition, subtraction, multiplication, and division) once we input both numbers.

Method 2: Calculator Program in Python using function

#Calculator Program in python by defining operations
# Define Operators or Functions: Addition, Subtraction, Multiplication, and Division
# Addition
def addition(n1, n2):    return n1 + n2
# Subtraction
def subtraction(n1, n2):    return n1 - n2
# Multiplication
def multiplication(n1, n2):    return n1 * n2
# Division
def division(n1, n2):    return n1 / n2

print("Select Operations")print(    "1. Addition\n"\    "2. Subtraction\n"\    "3. Multiplication\n"\    "4. Division\n")
# Giving the option to the user to choose the operation
operation = int(input("Enter choice of operation 1/2/3/4: "))

#Taking Input from the Users
n1 = float(input("Enter the First Number: "))n2 = float(input("Enter the Second Number: "))

# Apply Conditional Statements: To make operation as-per-user choices
if operation == 1:    print (n1, "+", n2, "=", addition(n1, n2))
elif operation == 2:    print (n1, "-", n2, "=", subtraction(n1, n2)) 
elif operation == 3:    print (n1, "*", n2, "=", multiplication(n1, n2))     elif operation == 4:    print (n1, "/", n2, "=", division(n1, n2))     else:    print("Invalid Input")
Copy code

Output

Explanation:

The above Program is created in three steps:

Step -1: Define Functions: Addition, Subtraction, Multiplication, and Division

Step-2: Promoting Input from the user

(i). Choosing which operation to perform

(ii). Enter the first and second numbers (float data type)

Step-3:  Apply Conditional Statements: To make operation as-per-user choices

Method 3: Creating a GUI calculator using tkinter in Python

#importing tkinter libraryimport tkinter as tkimport tkinter.messageboxfrom tkinter.constants import SUNKEN
window=tk.Tk()window.title('My Calci')frame=tk.Frame(master=window,bg="skyblue",padx=10)frame.pack()entry=tk.Entry(master=frame,relief=SUNKEN,borderwidth=3,width=30)entry.grid(row=0,column=0,columnspan=4,ipady=2,pady=2)
#define myclick function to get the input from the user
def myclick(number):    entry.insert(tk.END,number)
#define an equal function to evaluate the value# try-except is use to handle the error
def equal():    try:        y=str(eval(entry.get()))        entry.delete(0,tk.END)        entry.insert(0,y)    except:        tkinter.messagebox.showinfo("Error","Syntax Error")
#define clear function to delete the previous inputs
def clear():    entry.delete(0,tk.END)
# Buttons for the First Row# 9, 8, 7, +
button_1=tk.Button(master=frame,text='9',padx=15,pady=5,width=3,command=lambda:myclick(9))button_1.grid(row=1,column=0,pady=2)
button_2=tk.Button(master=frame,text='8',padx=15,pady=5,width=3,command=lambda:myclick(8))button_2.grid(row=1,column=1,pady=2)
button_3=tk.Button(master=frame,text='7',padx=15,pady=5,width=3,command=lambda:myclick(7))button_3.grid(row=1,column=2,pady=2)
#addition button (+)button_add=tk.Button(master=frame,text="+",padx=15,pady=5,width=3,command=lambda:myclick('+'))button_add.grid(row=1,column=3,pady=2)

#buttons for the second row# 6, 5, 4, -
button_4=tk.Button(master=frame,text='6',padx=15,pady=5,width=3,command=lambda:myclick(6))button_4.grid(row=2,column=0,pady=2)
button_5=tk.Button(master=frame,text='5',padx=15,pady=5,width=3,command=lambda:myclick(5))button_5.grid(row=2,column=1,pady=2)
button_6=tk.Button(master=frame,text='4',padx=15,pady=5,width=3,command=lambda:myclick(4))button_6.grid(row=2,column=2,pady=2)
#subtraction button (-)button_subtract=tk.Button(master=frame,text="-",padx=15,pady=5,width=3,command=lambda:myclick('-'))button_subtract.grid(row=2,column=3,pady=2)

#buttons for the third row# 3, 2, 1, and *
button_7=tk.Button(master=frame,text='3',padx=15,pady=5,width=3,command=lambda:myclick(3))button_7.grid(row=3,column=0,pady=2)
button_8=tk.Button(master=frame,text='2',padx=15,pady=5,width=3,command=lambda:myclick(2))button_8.grid(row=3,column=1,pady=2)
button_9=tk.Button(master=frame,text='1',padx=15,pady=5,width=3,command=lambda:myclick(1))button_9.grid(row=3,column=2,pady=2)
#multiply button (*)button_multiply=tk.Button(master=frame,text="*",padx=15,pady=5,width=3,command=lambda:myclick('*'))button_multiply.grid(row=3,column=3,pady=2)

#buttons for the fourth row# clear, 0, equal, and /
#clear buttonbutton_clear=tk.Button(master=frame,text="C",padx=15,pady=5,width=3,command=clear)button_clear.grid(row=4,column=0,pady=2)
# 0 buttonbutton_0=tk.Button(master=frame,text='0',padx=15,pady=5,width=3,command=lambda:myclick(0))button_0.grid(row=4,column=1,pady=2)
#equal buttonbutton_equal=tk.Button(master=frame,text="=",padx=15,pady=5,width=3,command=equal)button_equal.grid(row=4,column=2,pady=2)
#division button (/)button_div=tk.Button(master=frame,text="/",padx=15,pady=5,width=3,command=lambda:myclick('/'))button_div.grid(row=4,column=3,pady=2)

window.mainloop()
Copy code

Output

Now, you can perform any arithmetic operations here and will give syntax error if you give the wrong Input, such as:

Explanation

GUI or Graphical User Interface is an interactive (visual) way to interact with the computer. You can click to input your values and get the output. In the above method, we use the standard GUI library of Python, i.e., tkinter, which allows users to create fast and easy-to-use GUI applications.

In the above Program, firstly, we imported the tkinter library of Python; secondly, we created the frame for the window (i.e. the title of the window, its size, background colour etc.)
Thirdly, we define three functions: myclick, equal and clear to input the values, evaluate the value and delete the values, respectively. Finally, we created the buttons in four rows and four columns.

Conclusion

In conclusion, a calculator program in Python can be an incredibly powerful tool for anyone who works with numbers or data. Whether you’re a student, researcher, or professional, our calculator program can help you save time, increase accuracy, and streamline your workflows. In the article, we have discussed three different methods for creating a calculator program in Python.

Original article source at: https://www.naukri.com

#python