Как сделать калькулятор в python

Как сделать калькулятор в python

Создаем простой калькулятор в PyQt5

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Калькуляторы – это одни из самых простых приложений, которые идут по умолчанию в каждой версии Windows. Со временем их расширял для поддержки научных и программных режимов, однако на фундаментальном уровне все они одинаковы.

В этой небольшой статье мы реализуем рабочий стандартный калькулятор при помощи PyQt5. Здесь используется логика из трех частей, включая короткий стек, оператор и состояние. Базовые операции с памятью также используются.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Пока это реализовано под Qt, вы можете легко конвертировать логику в работу для работы в оборудовании при помощи MicroPython или Raspberry Pi.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Исходный код

Скачать: https://github.com/mfitzp/15-minute-apps/tree/master/calculator
Полный исходный код Calculon доступен в пятнадцатиминутном репозитории. Вы можете скачать\клонировать его для получения рабочей копии:

Затем установить все необходимые зависимости при помощи:

После этого вы можете запустить калькулятор при помощи:

Ознакомьтесь с тем, как работает код в путеводителе.

Пользовательский интерфейс

Пользовательский интерфейс «Calculon» был создан в Qt Designer. Макет mainwindow использует QVBoxLayout с LCD экраном добавленным вверху и QGridLayout внизу.

Мы используем макет сетки, который используется для позиционирования всех кнопок калькулятора. Каждая кнопка занимает одно место в сетке, кроме знака равно, который занимает две клетки.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Действия

Чтобы кнопки делали что-либо, нам нужно связать их с определенными обработчиками. Определенные связи показаны сначала внизу, затем подробно описанные обработчики.

Сначала мы подключаем цифровые кнопки к своим обработчикам. В Qt Designer мы назвали все кнопки, используя стандартный формат, так, в pushButton_nX литера Х является числом. Это упрощает их итерацию и подключение.

Мы используем оберточную функцию на сигнале для передачи дополнительной информации с каждым запуском. В нашем случае, введенное число от 0 до 9 используя функцию range.

Calculator Application using Tkinter (Python Project)

In this tutorial, we will cover how to create a simple calculator app using Python Tkinter.

As in our previous tutorials, we have covered how to create tkinter buttons, tkinter labels, tkinter entry, tkinter frames and tkinter checkbuttons, and many more. Now with the help of all the widgets discussed in previous sections, we are going to create a Calculator App using Tkinter.

Here is how our calculator will look, which is made by using the input field, buttons and for the calculation purpose we will use logic in our code defined in functions, like if you want to add two numbers then behind this there must be a logic for addition purpose, similarly for substraction, multiplication, etc, we have created functions whose task is to perform these operations.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

We have an Input Field in which the user input will be shown and the final result of the calculation will be displayed.

What is a Calculator?

For those who do not know, a calculator is basically a program on a computer that simulates the behavior of any hand-held calculator useful for performing Mathematical Calculations. It is a very basic device used in our everyday lives. Now all the smartphones also have a Calculator application in them.

While creating any GUI Application there are mainly two steps:

The first step is to create a User Interface.

The second step is the most important one and in this, to add functionalities to the GUI

Now let’s begin with creating a simple calculator app using Tkinter in Python which is used for basic arithmetic calculations.

Calculator App Code

Now it’s time to take a look at the code to create a Calculator App using Tkinter:

There are a variety of functions in Tkinter with the help of them it becomes easy and convenient to make a simple calculator just with this little code.

Apart from the Tkinter widgets, we have defined the following functions in our code:

btn_click() Function: This function handles the button click on various numeric buttons to add them to the operation.

bt_clear() Function: This function is used to handle the clear operation to clean the previous input in the Calculator application.

bt_equal() Function: This function is used to handle the equal button to execute the operation and show the result.

Now we will show you a snapshot as the output of the above code. And yes you can implement it on your system for more clear understanding of Calculator App Using Tkinter:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Summary:

In this tutorial, we developed a basic Calculator application using Tkinter and various widgets of Tkinter about which we have covered in our Tkinter Tutorial. Click on Next to see more Apps developed using Tkinter as this will help you practice what you have learned.

Python and PyQt: Building a GUI Desktop Calculator

Even as web and mobile applications appear to overtake the software development market, there’s still a demand for traditional Graphical User Interface (GUI) desktop applications. For developers who are interested in building these kinds of applications in Python, there are a wide variety of libraries to choose from, including Tkinter, wxPython, PyQt, PySide2, and others. In this tutorial, you’ll develop GUI desktop applications with Python and PyQt.

You’ll learn how to:

For this tutorial, you’ll create a calculator application with Python and PyQt. This will help you grasp the fundamentals and get you up and running with the library. You can download the source code for the project and all examples in this tutorial by clicking on the link below:

Download Code: Click here to download the code you’ll use to build a calculator in Python with PyQt in this tutorial.

Understanding PyQt

PyQt is a Python binding for Qt, which is a set of C++ libraries and development tools that include platform-independent abstractions for Graphical User Interfaces (GUI), as well as networking, threads, regular expressions, SQL databases, SVG, OpenGL, XML, and many other powerful features. Developed by RiverBank Computing Ltd, PyQt is available in two editions:

Even though PyQt4 can be built against Qt 5.x, only a small subset that is also compatible with Qt 4.x will be supported. This means that if you decide to use PyQt4, then you’ll probably miss out on some of the new features and improvements in PyQt5. See the PyQt4 documentation for more information on this topic.

You’ll be covering PyQt5 in this tutorial, as it seems to be the future of the library. From now on, be sure to consider any mention of PyQt as a reference to PyQt5.

Note: If you want to dive deeper into the differences between the two versions of the library, then you can take a look at the related page on the PyQt5 documentation.

PyQt5 is compatible with Windows, Unix, Linux, macOS, iOS, and Android. This can be an attractive feature if you’re looking for a library or framework to develop multi-platform applications with a native look and feel on each platform.

PyQt5 is available under two licenses:

Your PyQt5 license must be compatible with your Qt license. If you use the GPL version, then your code must also use a GPL-compatible license. If you want to use PyQt5 to create commercial applications, then you’ll need a commercial license for your installation.

Note: The Qt Company has developed and currently maintains its own Python binding for the Qt library. The Python library is called Qt for Python and is considered to be the official Qt for Python. In this case, the Python package is called PySide2.

As PyQt5 and PySide2 are both built on top of Qt, their APIs are quite similar, even almost identical. That’s why porting PyQt5 code to PySide2 can be as simple as updating some imports. If you learn one of them, then you’ll be able to work with the other with minimal effort. If you want to dive deeper into the differences between these two libraries, then you can check out the following resources:

Installing PyQt

You have several options to choose from when you install PyQt on your system or development environment. The first option is to build from source. This can be a bit complicated, so you might want to avoid it if possible. If you really need to build from source, then you can take a look at what the library’s documentation recommends in those cases.

Note: Most of the installation options you’ll cover here require that you have a working Python installation. If you need to dive deeper into how to install Python, then check out Python 3 Installation & Setup Guide.

Another option would be to use binary wheels. Wheels are a very popular way to manage the installation of Python packages. However, you need to consider that wheels for PyQt5 are only available for Python 3.5 and later. There are wheels for:

All of these wheels include copies of the corresponding Qt libraries, so you won’t need to install them separately.

System-Wide Installation With pip

If you’re using Python 3.5 or later, then you can install PyQt5 from PyPI by running the following command:

With this command, you’ll install PyQt5 in your base system. You can start using the library immediately after the installation finishes. Depending on your operating system, you may need root or administrator privileges for this installation to work.

Virtual Environment Installation With pip

You may decide not to install PyQt directly on your base system to avoid messing up your configuration. In this case, you can use a Python virtual environment. If you’re on a UNIX system, then you can use the following commands to create one and install PyQt5:

Platform-Specific Installation

In the Linux ecosystem, several distributions include binary packages for PyQt in their repositories. If this is true for your distribution, then you can install the library using the distribution’s package manager. On Ubuntu 18.04 for example, you can use the following command:

If you’re a Mac user, then you can install PyQt5 using the Homebrew package manager. To do that, open a terminal and type in the following command:

If all goes well, then you’ll have PyQt5 installed on your base system, ready for you to use.

Note: If you use a package manager on Linux or macOS, then there’s a chance you won’t get the latest version of PyQt5. A pip installation would be better if you want to ensure that you have the latest release.

If you really need to install PyQt this way, then you’ll need to:

Anaconda Installation

Another alternative you can use to install PyQt is Anaconda, a Python distribution for data science. Anaconda is a free and multi-platform package and environment manager that includes a collection of over 1,500 open source packages.

Anaconda provides a user-friendly installation wizard that you can use to install PyQt on your system. You can download the appropriate version for your current platform and follow the on-screen instructions. If you install the latest version of Anaconda, then you’ll have the following packages:

With this set of packages, you’ll have all that you need to develop GUI desktop applications with Python and PyQt.

Note: Note that the Anaconda installation will occupy a large amount of disk space. If you install Anaconda only to use the PyQt packages, then you’ll have a serious amount of unused packages and libraries on your system. Keep this in mind when you consider using the Anaconda distribution.

Creating Your First PyQt Application

Now that you have a working PyQt installation, you’re ready to start coding. You’re going to create a “Hello, World!” application with Python and PyQt. Here are the steps you’ll follow:

You can download the source code for the examples you’ll cover in this section at the link below:

Download Code: Click here to download the code you’ll use to build a calculator in Python with PyQt in this tutorial.

You’ll start with a file called hello.py in your current working directory:

For step two, you need to create an instance of QApplication as follows:

Every functional GUI application needs widgets! Here, you use a QLabel object ( helloMsg ) to show the message Hello World! on your application’s window. QLabel objects can accept HTML text, so you can use the HTML element ‘

Hello World!

Note: In PyQt5, you can use any widget (a subclass of QWidget ) as a top-level window, or even a button or a label. The only condition is that you pass no parent to it. When you use a widget like this, PyQt5 automatically gives it a title bar and turns it into a normal window.

The parent-child relationship is used for two complementary purposes:

This relationship also defines ownership, with parents owning their children. The PyQt5 ownership model ensures that if you delete a parent (for example, a top-level window), then all of its children (widgets) are automatically deleted as well.

You’re done with step three, so let’s code the last two steps and get your first PyQt GUI application ready to go live:

Note: A paint event is a request for painting the widgets that compose a GUI.

When you run this script, you should see a window like this:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Here, your application shows a window (based on QWidget ) with the message Hello World! on it. To show the message, you use a QLabel that contains the message in HTML format.

Congrats! You’ve created your first PyQt GUI desktop application!

Considering Code Styles

If you take a closer look at the code for your first application, then you’ll notice that PyQt doesn’t follow PEP 8 coding style and naming conventions. PyQt is built on top of Qt, which is written in C++ and uses a camelCase naming style for functions, methods, and variables. That said, you’ll need to decide what naming style you’re going to use for your own PyQt GUI applications.

With regard to this issue, PEP 8 states that:

New modules and packages (including third party frameworks) should be written to these standards, but where an existing library has a different style, internal consistency is preferred. (Source)

In addition, the Zen of Python says:

If you want to write consistent code, then you might want to disregard PEP 8 naming style and stick to the PyQt naming style. This is a decision that you need to make. In this tutorial, you’ll follow the PyQt naming style for consistency.

Learning the Basics of PyQt

You’ll need to master the basic concepts of PyQt logic in order to efficiently use the library to develop GUI applications. Some of these concepts include:

These elements will be the building blocks of your PyQt GUI applications. Most of them are represented as Python classes. PyQt5.QtWidgets is the module that provides all these classes. These elements are extremely important, so you’ll cover them in the next few sections.

Widgets

QWidget is the base class for all user interface objects, or widgets. These are rectangular-shaped graphical components that you can place on your application’s windows to build the GUI. Widgets contain a series of attributes and methods that allow you to model their appearance and behavior. They can also paint a representation of themselves on the screen.

Widgets also receive mouse clicks, keypresses, and other events from the user, the window system, and many other sources. Each time a widget catches an event, it emits a signal to announce its state change. PyQt5 has a rich and modern collection of widgets that serve several purposes. Some of the most common and useful widgets are:

Buttons like these are perhaps the most commonly used widget in any GUI. When you click them, you can command the computer to perform actions. You can even perform actions in response to a user clicking a button.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

You can use labels like these to better explain the purpose or usage of your GUI. You can tweak their appearance in several ways, and they can even accept HTML text, as you saw earlier. Labels can also be used to specify a focus mnemonic key for another widget.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

This combo box is read-only, which means the user can select one of several options but can’t add their own. Combo boxes can also be editable, allowing the user to add new options. They can contain pixmaps, strings, or both.

In this group of radio buttons, only one button can be checked at a given time. If the user selects another radio button, then the previously selected button will switch off automatically.

PyQt5 has a large collection of widgets. At the time of this writing, there are over forty available for you to use to create your application’s GUI. Those you’ve covered so far are only a small sample, but they show you the power and flexibility of PyQt5. In the next section, you’ll cover how to lay out different widgets to create modern and functional GUIs for your applications.

Layout Managers

Layout managers are classes that allow you to size and position your widgets at the places you want them to be on the application’s form. Layout managers automatically adapt to resize events and content changes. They also control the size of the widgets within them. This means that the widgets in a layout are automatically resized whenever the form is resized.

Note: If you develop international applications, then you may have seen how translated labels can be cut short. This is particularly likely when the target language is more verbose than the original language. Layout managers can help you avoid this common pitfall. However, this feature can be a bit tricky and can sometimes fail with particularly wordy languages.

PyQt provides four basic layout manager classes:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

The widgets will appear one next to the other, starting from the left.

This code example shows you how to use QHBoxLayout to arrange buttons horizontally:

The highlighted lines do the magic here:

When you run python3 h_layout.py from your command line, you’ll get the following output:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

In the above figure, you added three buttons in a horizontal arrangement. Notice that the buttons are shown from left to right in the same order as you added them in your code.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Each new widget will appear beneath the previous one. You can use this class to construct vertical box layout objects and organize your widget from top to bottom.

Here’s how you can create and use a QVBoxLayout object:

When you run this application, you’ll get an output like this:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

This application shows three buttons in a vertical layout, one below the other. The buttons appear in the same order as you added them in your code, from top to bottom.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Here’s how to use QGridLayout in your GUI:

If you run this code from your command line, then you’ll get a window like this:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

You can see your widgets arranged in a grid of rows and columns. The last widget occupies more than one cell, as you specified in line 23.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

The left column consists of labels, and the right column consists of field widgets. If you’re dealing with a database application, then this kind of layout can be an attractive option for increased productivity when you’re creating your forms.

The following example shows you how to create an application that uses a QFormLayout object to arrange its widgets:

If you run this code, then you’ll get the following output:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

The above figure shows a GUI that uses a form layout. The first column contains labels to ask the user for some information. The second column shows widgets that allow the user to enter or edit the information you asked from them.

Dialogs

With PyQt, you can develop two types of GUI desktop applications. Depending on the class you use to create the main form or window, you’ll have one of the following:

You’ll start with Dialog-Style applications first. In the next section, you’ll cover Main Window-Style applications.

Note: Dialog windows are also commonly used in Main Window-Style applications for brief communication and interaction with the user.

When dialog windows are used to communicate with the user, they may be:

Dialog windows can also provide a return value and have default buttons (for example, OK and Cancel ).

Here’s an example of how you’d use QDialog to develop a Dialog-Style application:

This application is a bit more elaborate. Here’s what’s going on:

The code block above displays the following window:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

This is the GUI that you created using QFormLayout for the widgets and QVBoxLayout for the general application’s layout ( dlgLayout in line 20).

Main Windows

Most of the time, your GUI applications will be Main Window-Style. This means that they’ll have a menu bar, some toolbars, a status bar, and a central widget that will be the GUI’s main element. It’s also common that your apps will have several dialog windows to accomplish secondary actions that depend on user input.

You’ll use the class QMainWindow to develop Main Window-Style applications. You need to inherit from QMainWindow to create your main GUI class. An instance of a class that derives from QMainWindow is considered to be a main window. QMainWindow provides a framework for building your application’s GUI. The class has its own built-in layout, which you can use to place the following:

One menu bar is at the top of the window. The menu bar holds the application’s main menu.

One central widget is in the center of the window. The central widget can be of any type, or it can be a composite widget.

Several dock widgets are around the central widget. Dock widgets are small, movable windows.

One status bar is at the bottom of the window. The status bar shows information on the application’s general status.

The following code example shows you how to use QMainWindow to create a Main Window-Style application:

Here’s how this code works:

Note: When you implement different GUI components in their own method, you’re making your code more readable and more maintainable. This is not a requirement, however, so you’re free to organize your code in the way you like best.

When you run the above code, you’ll see a window like the following:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

You can see that your Main Window-Style application has the following components:

So far, you’ve covered some of the more important graphical components of PyQt5’s set of widgets. In the next two sections, you’ll cover some other important concepts related to PyQt GUI applications.

Applications

One of the most important responsibilities of QApplication is to provide the event loop and the entire event handling mechanism. Let’s take a closer look at the event loop now.

Event Loops

GUI applications are event-driven. This means that functions and methods are executed in response to user actions like clicking on a button, selecting an item from a combo box, entering or updating the text in a text edit, pressing a key on the keyboard, and so on. These user actions are generally called events.

Events are commonly handled by an event loop (also called the main loop). An event loop is an infinite loop in which all events from the user, the window system, and any other sources are processed and dispatched. The event loop waits for an event to occur and then dispatches it to perform some task. The event loop continues to work until the application is terminated.

Event loops are used by all GUI applications. The event loop is kind of an infinite loop that waits for the occurrence of events. If an event happens, then the loop checks if the event is a Terminate event. In that case, the loop is terminated and the application exits. Otherwise, the event is sent to the application’s event queue for further processing, and the loop starts again.

PyQt5 targets Python 3, which doesn’t have an exec keyword. Still, the library provides two methods that start the event loop:

For an event to trigger a response action, you need to connect the event with the action you want to be executed. In PyQt5, you can establish that connection by using the signals and slots mechanism. You’ll cover these in the next section.

Signals and Slots

PyQt widgets act as event-catchers. This means that every widget can catch a specific number of events, like mouse clicks, keypresses, and so on. In response to these events, widgets always emit a signal, which is a kind of message that announces a change in its state.

The signal on its own doesn’t perform any action. If you want a signal to trigger an action, then you need to connect it to a slot. This is the function or method that will perform an action whenever the connecting signal is emitted. You can use any Python callable (or callback) as a slot.

If a signal is connected to a slot, then the slot is called whenever the signal is emitted. If a signal isn’t connected to any slot, then nothing happens and the signal is ignored. Here are some of the most useful features of this mechanism:

You can use the following syntax to connect a signal to a slot:

This code shows you how to use the signals and slots mechanism:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Note: Every widget has its own set of predefined signals. You can check them out on the widget’s documentation page.

The signals and slots mechanism is what you’ll use to give life to your PyQt5 GUI applications. This mechanism will allow you to turn user events into concrete actions. You can dive deeper into the signals and slots mechanism by taking a look at the PyQt5 documentation.

Now you’ve finished covering the most important concepts of PyQt5. With this knowledge and the library’s documentation at hand, you’re ready to start developing your own GUI applications. In the next section, you’ll build your first fully-functional GUI application.

Creating a Calculator With Python and PyQt

In this section, you’re going to develop a calculator using the Model-View-Controller (MVC) design pattern. This pattern has three layers of code, each with different roles:

The model takes care of your app’s business logic. It contains the core functionality and data. For your calculator, the model will handle the calculations.

The view implements your app’s GUI. It hosts all the widgets the end-user would need to interact with the application. The view also receives user actions and events. For your calculator, the view will be the window you’ll see on your screen.

The controller connects the model and the view to make the application work. User events (or requests) are sent to the controller, which puts the model to work. When the model delivers the requested result (or data) in the right format, the controller forwards it to the view. For your calculator, the controller will receive user events from the GUI, ask the model to perform calculations, and update the GUI with the result.

Here’s a step-by-step MVC pattern for a GUI desktop application:

You’ll use this MVC design pattern to build your calculator.

Creating the Skeleton

Download Code: Click here to download the code you’ll use to build a calculator in Python with PyQt in this tutorial.

If you’d prefer to code the project on your own, then go ahead and create pycalc.py in your current working directory. Then, open the file in your code editor and type the following code:

This script implements all the code you’ll need to run a basic GUI application. You’ll use this skeleton to build your calculator. Here’s how it works:

When you run the script, the following window will appear on your screen:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

This is your GUI application skeleton.

Completing the View

The GUI you have at this point doesn’t really look like a calculator. Let’s finish the GUI by adding the display and buttons for the numbers. You’ll also add buttons for basic math operations and for clearing the display.

First, you’ll need to add the following imports to the top of your file:

You’re going to use a QVBoxLayout for the calculator’s general layout. You’ll also use a QGridLayout object to arrange the buttons. Finally, you import QLineEdit for the display and QPushButton for the buttons. There should now be eight import statements at the top of your file.

Now you can update the initializer for PyCalcUi :

Here, you’ve added the highlighted lines of code. You’ll use a QVBoxLayout to place the display at the top and the buttons in a grid layout at the bottom.

To create the display widget, you use a QLineEdit object. Then you set the following display properties:

Now, the calculator’s GUI (or view) can show the display and the buttons. But there’s still no way to update the information shown in the display. You can fix this by adding a few extra methods:

These methods will form the GUI public interface and complete the view class for your Python calculator. Here’s a possible implementation:

Here’s what each function does:

.clearDisplay() sets the display’s text to an empty string ( » ) so the user can introduce a new math expression.

Now your calculator’s GUI is ready! When you run the application, you’ll see a window like this one:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

You’ve completed the calculator’s GUI interface. However, if you try to do some calculations, then you’ll notice that the calculator doesn’t do anything just yet. That’s because you haven’t implemented the model or the controller. Next, you’ll add a basic controller class to start giving life to your calculator.

Creating a Basic Controller

In this section, you’re going to code the calculator’s controller class. This class will connect the view to the model. You’ll use the controller class to make the calculator perform actions in response to user events. You’ll start with the following import:

Your controller class needs to perform three main tasks:

This will ensure that your calculator is working correctly. Here’s how you code the controller class:

For this new controller class to work, you need to update main() :

This code creates an instance of PyCalcCtrl(view=view) with the view passed in as an argument. This will initialize the controller and connect the signals and slots to give your calculator some functionality.

If you run the application, then you’ll see something like the following:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

As you can see, the calculator already has some useful functionalities! Now, you can build math expressions by clicking on the buttons. Notice that the equals sign ( = ) doesn’t work yet. To fix this, you need to implement the calculator’s model.

Implementing the Model

The model is the layer of code that takes care of the business logic. In this case, the business logic is all about basic math calculations. Your model will evaluate the math expressions introduced by your users. Since the model needs to handle errors, you’re going to define the following global constant:

This is the message the user will see if they introduce an invalid math expression.

Your model will be a single function:

Here, you use eval() to evaluate a string as an expression. If this is successful, then you’ll return the result. Otherwise, you’ll return the error message. Note that this function isn’t perfect. It has a couple of important issues:

You’re free to rework the function to make it more reliable and secure. For this tutorial, you’ll use the function as-is.

Completing the Controller

Once you’ve completed the calculator’s model, you can finish the controller. The final version of PyCalcCtrl will include logic to process the calculations and to make sure the equals sign ( = ) works correctly:

For all this code to work, you need to update main() :

Running the Calculator

Now that you’ve finished the code, it’s time for a test! If you run the application, then you’ll see something like this:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

To use PyCalc, enter a valid math expression with your mouse. Then, press Enter or click on the equals sign ( = ) to see the result on the calculator’s display.

Congrats! You’ve developed your first fully-functional GUI desktop application with Python and PyQt!

Additional Tools

PyQt5 offers quite a useful set of additional tools to help you build solid, modern, and full-featured GUI applications. Here are some of the most remarkable tools you can use:

Qt Designer is the Qt tool for designing and building graphical user interfaces. You can use it to design widgets, dialogs, or complete main windows by using on-screen forms and a drag-and-drop mechanism. The following figure shows some of the Qt Designer’s features:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Conclusion

Graphical User Interface (GUI) desktop applications still hold a substantial share of the software development market. Python offers a handful of frameworks and libraries that can help you develop modern and robust GUI applications.

In this tutorial, you learned how to use PyQt, which is arguably one of the most popular and solid libraries for GUI desktop application development in Python. Now you know how to effectively use both Python and PyQt to build modern GUI desktop applications.

You’re now able to:

Now you can use Python and PyQt to give life to your desktop GUI applications! You can get the source code for the calculator project and all code examples at the link below:

Download Code: Click here to download the code you’ll use to build a calculator in Python with PyQt in this tutorial.

Further Reading

If you want to dive deeper into PyQt and its related tools, then you can take a look at some of these resources:

Although the PyQt5 Documentation is the first resource listed here, some important parts are still missing or incomplete. Fortunately, you can use the PyQt4 Documentation to fill in the blanks. The Class Reference is particularly useful for gaining a complete understanding of widgets and classes.

If you’re using the PyQt4 documentation as a reference for PyQt5 classes, then bear in mind that the classes will be slightly different and may behave differently, too. Another option would be to use the original Qt v5 Documentation and its Class Reference instead. In this case, you may need some background in C++ to properly understand the code samples.

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

About Leodanis Pozo Ramos

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Leodanis is an industrial engineer who loves Python and software development. He’s a self-taught Python developer with 6+ years of experience. He’s an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Master Real-World Python Skills With Unlimited Access to Real Python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Оконный калькулятор на Python с Tkinter

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

В этой статье мы разберём как сделать калькулятор на Python с использованием библиотеки Tkinter, для создания графического интерфейса или оконного приложения.

Также можете посмотреть прошлую часть где мы познакомились с этой библиотекой, статья называется «Создание графического интерфейса в Python», думаю будет интересно.

Калькулятор на на Python с Tkinter:

Перед тем как начать работать, нужно установить все нужные компоненты, но нам нужно скачать только Tkinter, для этого как всегда для Python прописываем команду PIP.

После того как скачали можете приступать к работе, для этого переходим в ваш файл, где вы будите хранить весь код.

Первым делом нужно импортировать нужные компоненты и создать переменные которые нам пригодятся:

Первым делом мы тут как всегда всё импортируем, потом создаём приложение и задаём ему заголовок, потом создаём кортеж кнопок, где каждый картеж, это отдельная строчка кнопок в приложение.

последние мы создаём переменную activeStr, которая отвечает за наспанные числа в строчки ввода, и вторая переменная это список, чисел и команда которые нужно будет выполнить.

Дальше создадим функцию которая будет считать получившийся результат, вот как она будет выглядеть:

Как видите в начале функции мы всё раскладываем на числа которые мы получаем и знаки на которые мы нажали, потом всё зависимо от от знака мы считаем вмести эти два числа и в вставляем это в нашу строку ввода.

Теперь перейдём к функции которая будет обрабатывать клик на кнопки там всё гораздо интереснее на мой взгляд.

В начале мы тут проверяем, а нажата ли кнопка CE, если да, то тогда всё удаляем и выводим ноль, иначе если были нажаты цифры, то добавляет это всё в поле ввода, если точка нажата, то тоже добавляем в поле.

Иначе проверяем если у нас stack больше или равен двум, то считаем что у нас получилось и выводим число в поле, которое получилось и если не было нажата равно, то вставляем это число в stack.

Иначе опять проверяем не было ли нажата равно, если нет, то всё так же добавляем значения в список stack.

Последние что нам осталось, так это отрендарить всё приложение, это будет не очень cложно.

По сути мы тут будем создавать таблицу но вначале делаем поле, и потом уже саму таблицу, после того как мы это сделали, первое создаём кнопку «CE», дальше рендрим остальные кнопки, по четыре столбца, это важно, и последние задаём конфигурации для строчки и столбцов, видь как вы поняли по сути мы работаем с таблицей.

Последние запускаем событие цикл который будет отслеживать события нажатия на кнопки, или если по простому то рендерим приложение.

Вывод:

В этой не большой статье вы прочитали как сделать калькулятор на Python с использованием библиотеки Tkinter, думаю вам было интересно, но рекомендую вам самим написать этот код, и поэкспериментировать над ним, чтобы всё ещё лучше понять, как он работает.

Как построить калькулятор GUI, используя Tkinter в Python?

В этой статье сегодня мы узнаем, как создать простой калькулятор GUI, используя TKinter. Мы поймем весь код шаг за шагом.

В этой статье сегодня мы узнаем, как создать простой калькулятор GUI, используя TKinter. Мы поймем весь код шаг за шагом.

Начало работы с нашим калькулятором GUI, используя Tkinter

Прежде чем мы начнем, убедитесь, что у вас есть библиотека TKinter, установленная для Python. Tkinter – это стандартная библиотека GUI для языка программирования Python. Когда Python объединяется с TKinter, он обеспечивает быстрый и простой способ создания приложений графического пользовательского интерфейса.

TKINTER предоставляет мощный объектно-ориентированный интерфейс для TK GUI Toolkit. Если TKINTER не установлен в вашем Python, откройте Windows CMD и введите следующую команду.

Tkinter Modelbox.

MessageBox – виджет в библиотеке Tkinter Python. Он используется для отображения ящиков сообщений в приложениях Python. Этот модуль используется для отображения сообщения с использованием определенного количества функций.

Параметры :

Варианты: Есть два варианта, которые можно использовать:

Структура калькулятора GUI с использованием Tkinter

Python Tkinter Label: Этикетка используется для указания коробки контейнера, где мы можем разместить текст или изображения. Этот виджет используется для предоставления сообщения пользователям о других виджетах, используемых в приложении Python.

Падры Python: Рамка – это только виджет. Рамы в Python – это не что иное, как простые контейнеры для его дочерних элементов. Используя их, мы можем дать дочерним контейнерам Mainframes, и мы можем разделить всю рамку макета по кадрам.

Предположим, мы запустим программу, у нас есть метка в начале, а затем несколько кнопок в корневом окне. Мы можем разделить эту часть корневой окна с помощью детали E.g этикетка как одна часть, а затем кнопки в разную часть. Если мы поместим эти части в один кадр, то этот кадр станет родительским элементом. Это поможет нам упростить сложный дизайн.

После добавления кадров структура калькулятора будет похожа:

Кнопки Python: Виджет кнопки используется для добавления кнопок в приложении Python. Эти кнопки могут отображать текст или изображения, которые передают цели кнопок. Вы можете прикрепить функцию или метод к кнопке, которая называется автоматически при нажатии кнопки.

1. Определение функций

Здесь мы начнем с кодировки для кнопок.

Мы определим первую функцию имени btn_1_isclicked () Отказ Мы даем это ущербное имя, так что нам становится легче понять, что функция на самом деле делает только что посмотрела на нее.

Здесь мы хотим, когда мы нажимаем на любую кнопку номера, мы хотим, чтобы это число было отображаться на нашей этикетке и хранить его в другой переменной, чтобы она была легко рассчитана.

Мы принимаем переменную глобально, чтобы избежать проблемы с именем переменной. В Python переменная, объявленная вне функции или в глобальном объеме, известна как глобальная переменная.

Это означает, что Глобальная переменная Доступ к доступу внутри или снаружи функции. Валь вот глобальная переменная. В приведенном выше коде мы создали Val в качестве глобальной переменной и определенной btn_1_isclicked () Чтобы распечатать глобальную валюту VAL и хранить его значение.

Выполните те же шаги для всех кнопок TKINTER.

2. Создание окна для нашего калькулятора GUI с помощью TKinter

Чтобы инициализировать TKinter, мы должны создать виджет TK CORT, который является окном с строкой заголовка и другие украшения, предоставляемые оконным менеджером.

Корневое окно – это главное окно приложения в наших программах. У него есть заголовка и границы.

Они предоставляются оконным менеджером. Он должен быть создан перед любыми другими виджетами.

Геометрия Метод устанавливает размер для окна и позиционирует его на экране. Первые два параметра являются ширина и высота окна. Последние два параметра являются координатами экрана x и y.

По установке root.Resizable до (0,0) программатор не сможет изменить размер окна. Лучше использовать root.resizable (0,0), потому что он сделает калькулятор на месте.

3. Настройка форматирования метки

Метка – это окно дисплея, где вы можете разместить текст или изображения. Текст, отображаемый этим виджетом, может быть обновлен в любое время. Также можно подчеркнуть часть текста (например, для идентификации сочетания клавиш) и охватить текст по нескольким строкам.

Родитель ярлыка является корнем. Это означает, что он не будет ограничен на один кадр, но целое root Window. Затем мы поставим простой текст, который мы будем динамически изменяться по всему коду до цифровых кнопок, которые мы нажимаем, отображается на метке.

Tkinter Stringvar Помогите вам управлять значением виджета, такого как метку или запись более эффективно. Контейнер – это виджет, который Stringvar объект, связанный с. Если вы пропустите контейнер, он по умолчанию для корневого окна значение – это начальное значение, которое по умолчанию по умолчанию для пустой строки.

Якорь : Он контролирует, где текст расположен, если виджет имеет больше места, чем потребности в тексте. По умолчанию (виджет будет размещен в правом нижнем углу рамки).

TextVariable: Чтобы иметь возможность извлечь текущий текст из вашего въезда в виджете, вы должны установить эту опцию в экземпляр данных stringvar класса I.e

4. Упаковка кнопок на окне

Рамка – виджет в Python. Это очень важно для процесса группировки и организации других виджетов как-то дружелюбным способом. Он работает как контейнер, который отвечает за организацию положения других виджетов.

Он использует прямоугольные зоны на экране для организации макета и обеспечить прокладку этих виджетов.

Рамка также может использоваться в качестве класса фундамента для реализации сложных виджетов.

Мы даем имя переменной к славе как BTNROW1 Отказ Синтаксис для кадра:

Затем мы упаковываем кадр. Повторите одни и те же шаги для трех трех кадров, вызывая корневое окно.

5. Добавление кнопок в наш калькулятор GUI с помощью TKinter

Виджет кнопки используется для добавления кнопок в нашем калькуляторе GUI, используя библиотеку Tkinter в Python. Эти кнопки могут отображать текст или изображения, которые передают цели кнопок. Вы можете прикрепить функцию или метод к кнопке, которая называется автоматически при нажатии кнопки.

Рельеф: С значением по умолчанию. Вы можете установить эту опцию для любого из других стилей, таких как: затонувший, жесткий, поднятый, плоский.

команда Является ли функция или метод, который будет называться, когда кнопка нажала. Здесь мы называем Команда, Функция, которую мы создали ранее, чтобы выполнить задачу.

Мы следуем тому же методу для других кнопок тоже.

Наконец, мы входим в MainLoop. Обработка событий начинается с этого момента. MainLoop получает события из оконной системы и отправляет их в виджеты приложений. Он прекращается, когда мы нажимаем на кнопку закрытия заголовка или вызовите Quit () метод.

Заключение

В этой статье мы покрыли кнопки TKINT, кадры, этикетки и его функциональные возможности, окна TKinter, входные коробки и то, как все эти все могут быть собраны для создания приложений GUI. Понимая код, мы добились успеха в создании рабочего калькулятора GUI с использованием библиотеки TKinter и его виджетов. Надеюсь, эта статья поможет.

Python Calculator – Create A Simple GUI Calculator Using Tkinter

Hey python developers, in Python Calculator tutorial you will learn to create a simple GUI calculator. In this post i will show you how to develop a simple calculator using tkinter module in python. So let’s move further to create a simple python calculator.

Python offers a lot of options to develop GUI applications, but Tkinter is the most usable module for developing GUI(Graphical User Interface). Since Tkinter is cross-platform so it works on both windows and Linux. So here i am using Tkinter module to create a simple python calculator.

Python Calculator Tutorial – Getting Started With Tkinter

The fastest and easiest way of developing GUI applications in python is working with Tkinter. So let’s took a quick look on Tkinter.

What is Tkinter

Prerequisite For Python Calculator

For developing a simple GUI calculator in python you must have to prior knowledge of following –

Look Of A Simple GUI Python Calculator

Look at this calculator. Yup this is looking very cool. So now we have to create this calculator in python.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

On this calculator we can perform following simple mathematical calculations –

And now we will start writing codes for making this. To create this we have to do four things –

Creating Window For Calculator

First of all we will create a window of calculator. So write the following code.

Let’s see the output.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

We have created this frame successfully, now lets move on ahead.

Adding Display Widget

For creating display widget write the following code inside the class app.

So now the output is –

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

Adding Clear Button Widget

Now we will create a clear button. Whenever this button will be pressed all the stuffs from display will be erased. So write the following code for this.

And now you can see the output.

Adding Numbers And Symbols Widget

To add numbers and symbols inside the frame, you have to write the following code.

And now you can see the output. It’s looking cool.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

Adding Equal Button

For implementing Equal button write the following code.

So now our calculator looks like as below.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

Applying Event Trigger On Widgets

Now the last thing but very important is to apply event triggers on widgets. It means whenever you click any widget some function will be performed. So write the following code

Complete Code For Python Calculator

So now i am collecting and keeping all the above codes in one place. So our entire code for making a simple calculator in python is below.

So now its time to see the calculator and you can perform any operation on it. So let’s start your calculation.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonPython Calculator

Congratulations, We have created python calculator successfully, that’s pretty cool, and i hope you have really enjoyed while making this. So surely comment your feelings about this.

Recommended Articles

So Guys this was all about the Python Calculator Tutorial. I hope, you liked it and if it is helpful for you then please share it with others and help them in learning python. And if you have any question regarding this post then leave your queries in comment section. In upcoming posts i will come with some interesting python applications, and if you want to learn making any particular application then suggest me your idea, i will try to fulfill your need. Thanks All of you.

Введение в Python

Поиск

Новое на сайте

Графический калькулятор квадратных уравнений на Python и Tkinter

Часть первая: функция решения квадратного уравнения.

Напомним, что квадратным является уравнение вида:

Есть несколько способов решить квадратное уравнение, мы выберем решение через дискриминант.

Используя эту формулу мы можем вывести решение. Если дискриминант больше или равен нулю, то корни уравнения высчитываются по формуле:

Если же дискриминант меньше нуля, то уравнение не имеет решений.

Превратим данные формулы в код:

Чтобы все работало не забудьте импортировать функцию sqrt из модуля math.

Теперь пора переходить к созданию графической оболочки для нашего приложения.

Часть вторая: создаем GUI для программы

Для простоты будем создавать GUI встроенными средствами Python, поэтому импортируем все из библиотеки Tkinter:

Далее создаем само окно и размещаем на нем необходимые виджеты:

Если вы в точности повторили указанный код, то после запуска скрипта у вас получится примерно следующее окно:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Отлично, программа работает. Осталось объяснить Python как связать эти две части.

Часть третья: объединяем все воедино

Функция вставки информации:

Функция inserter предельно проста: очищает поле для ввода и вставляет туда переданный ей аргумент value.

Напишем функцию обработки введенной информации. Назовем ее handler:

В зависимости от данных введенных в поля для ввода передает функции inserter либо результат решения уравнения, либо сообщение о неверно введенных данных.

Чтобы все работало, следует изменить строку создания виджета Button следующим образом:

Теперь можно спокойно пользоваться нашей программой:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonКак сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python
Дискриминант больше нуляДискриминант равен нулю
Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonКак сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python
Дискриминант меньше нуля. Решений нетВведены не все аргументы

Часть четвертая: необязательная

Можно добавить немного удобства для нашей программы. Проблема в том, что каждый раз вводя новые значения нам приходится удалять старые, что не очень комфортно. Напишем функцию, которая будет очищать поле для ввода после клика по нему.

Готово. Программа работает, Вы великолепны!

Исходный код калькулятора квадратных уравнений с GUI на GitHub

Простой GUI калькулятор на Python #3

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Штош. Дописываем калькулятор. Если вы не читали прошлую статью, я вам настоятельно рекомендую это сделать.

Добавляем отрицание

Логика проста: если отрицания нет в поле, значит добавляем. Иначе убираем левый символ с помощью среза [1:]. Не забываем ввести дополнительное условие для нуля.

Возникает такая проблемка: при максимальной длине отрицание вытесняет последнюю цифру. Так работать, конечно же, не должно.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Давайте добавим в конструктор переменную максимальной длины поля ввода. Взять её можно с помощью метода maxLength.

Если длина строки больше этой переменной на единицу и в строке есть отрицание, то ставим максимальную длину поля больше на единицу. Иначе ставим обратно дефолтную максимальную длину.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Backspace

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Удаляем равенство из Label

Когда во временном выражении есть равенство, следующая нажатая кнопка должна удалять его из лейбла.

Но удалять должна не любая кнопка, а цифра, точка, отрицание, Backspace и очищение поля ввода.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Обрабатываем исключения

При нажатии на кнопку «равно», когда во временном выражении уже есть равенство, программа выкидывает KeyError.

Напишем метод для показа ошибки, передадим в него текст. Сначала ставим максимальную длину поля, равную длине текста ошибки, а затем уже ставим сам текст.

Если число в лейбле равно нулю, то ставим ошибку «результат не определен». Иначе ставим простое сообщение о делении на ноль.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Убираем ошибки

Если текст в поле равен какой-то ошибке, то ставим максимальную длину поля обратно к дефолтному значению и ставим текст 0

Убирать ошибку нужно в начале методов добавления цифры, backspace и очищения полей. Почему только они? Мы заблокируем кнопки знаков, точки и отрицания.

Блокируем кнопки

Блокируем кнопки в конце метода показа ошибки.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Смотрите, на кнопки нельзя кликнуть, но по интерфейсу так сразу и не скажешь, пока не наведёшь. Нужно сделать текст кнопок серым.

Меняем цвет кнопок

Напишем метод изменения цвета кнопок. Мы будем передавать в него css строку с цветом.

Для блокировки у нас будет серый цвет #888.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Включаем кнопки

Передаем логическую переменную в метод блокировки и ставим её же в setDisabled для кнопок.

Еще нужно вернуть кнопкам белый цвет.

Проставим в методы показа и удаления ошибки.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Регулируем размер шрифта

Для начала введем 2 переменные с размерами шрифтов:

Теперь создадим методы получения ширины текста в пикселях для поля и лейбла:

Регулируем размер шрифта в поле ввода. Пока ширина текста больше ширины окна (-15, так будет лучше), мы уменьшаем размер шрифта на единицу.

Нужно проставить этот метод после любого изменения длины текста в поле ввода.

Ставим после self.ui.le_entry.setText*

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Мы только уменьшаем размер шрифта, нужно его еще увеличивать при уменьшении ширины текста и увеличении ширины окна.

Пока ширина текста меньше ширины поля (-60, так будет лучше), увеличиваем размер шрифта, но не больше дефолтного значения.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Как регулировать размер шрифта при изменении ширины окна приложения? Очень просто, нужно использовать встроенный resizeEvent:

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Регулируем размер шрифта во временном выражении

То же самое проворачиваем для временного выражения.

Ставим после self.ui.lbl_temp.setText* и self.ui.lbl_temp.clear()

Делаем код немного компактнее

Вообще это можно было сделать в самом начале, но мы сделаем в самом конце.

Заменим во всем коде:

self.ui.le_entry на self.entry

self.ui.lbl_temp на self.temp

Введем 2 переменные для поля и временного выражения в конструкторе класса:

Проблема с вычислениями вещественных чисел

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Эта проблема не связана конкретно с питоном, она присутствует и в других языках, вот вам пример в JavaScript.

Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Все дело в том, что вещественные числа не могут быть точно представлены из-за особенностей их реализации в двоичном виде. Если вы заинтересовались темой, вы можете посмотреть про арифметику вещественных чисел и про стандарт 754.

Ну а как бороться с этой проблемой? Можно использовать модуль decimal, вот пример его работы:

Вот вам и задача со звездочкой, переделайте вычисления калькулятора с этим модулем.

Заключение

Конечно, можно найти еще уйму изъянов в работе калькулятора, но я и не претендую заменить системный. Зачем? Я думаю, получилось вполне неплохо относительно уже существующих туториалов на калькуляторы в интернетах, и надеюсь, что помог вам с изучением этого змеиного языка.

Создаем продвинутый калькулятор на Python с Tkinter

Здравствуйте! В этой публикации я хочу рассказать Вам, как сделать продвинутый калькулятор на Python 3 с Tkinter.

Итак, импортируем модули, которые нам понадобятся для нашей программы.
Библиотека tkinter нам необходима для создания окна, грубо говоря.
Модуль math нам нужен для математических операций.

Следующими двумя строками мы создаем окно и даем ему имя.

Создаем список с именами будущих кнопок калькулятора. Я выбрал все самые интересные функции, чтобы продемонстрировать, как их реализовать.

Следующим отрезком кода мы создаем кнопки для нашего калькулятора.

В каждом калькуляторе есть, так называемое поле ввода, в которое пользователь вводит нужные данные для программы. Это могут быть цифры, функции и математические операции. Их можно вводить, как с клавиатуры, так и при нажатии на кнопку в калькуляторе.

Пример 1. Я нажимаю на кнопку «2» в калькуляторе и в этом поле ввода, отображается цифра 2.

В Python Tkinter поле ввода называется Entry, а, например, в Java Script — input.

Мы подошли к основной задаче калькулятора — его функциям и логике.
До этого момента нами было создан внешний вид программы. Если бы Вы попробовали запустить ее и нажать на кнопку, Вам бы выскочила ошибка, ведь у нас вовсе нет функций калькулятора.
Приступим, пропишем нашему калькулятору логику и способность считать.

Создаем функцию очищения поля ввода. Она будет срабатывать при нажатии на кнопку «C».

Следующая функция — число pi. При нажатии на кнопку «П» программа выведет нам 3.14159265359, то есть число Pi. Вот тут нам и пригодилась библиотека math.

Функция выхода из программы. При нажатии на кнопку «Exit» окно Tkinter будет уничтожено и процесс остановлен. В этой функции нам нужна была библиотека sys.

Функция возведения в степень. Нужно ввести число, которое нужно возвести в степень. Далее программа выводит **. В Python этот символ означает возведение в степень 2**6 (возведение 2 в степень 6). Мы используем для счета в программе eval, а значит можно выполнить это так же, как и в Питоне. Ну и в конце мы вводим необходимую степень.
Пример 3. Нам нужно 3 возвести в 5 степень. Вводим число 3, нажимаем на кнопку «xⁿ» (3**. ) и вводим необходимую степень, — 5 (3**5). Нажимаем на кнопку «=» и получаем ответ 243.

Опишу сразу две функции, так, как они идентичны.
Функция sin x и cos x.
Все просто, при нажатии на клавишу sin или же cos мы получаем синус или косинус по данному числу.

Следующие две функции — скобки ) и (.
При нажатии на кнопку «)» мы получаем ), аналогично поступаем со второй функцией.

Функция получения факториала из данного числа.

Функция извлечения корня квадратного их данного числа.

Функция, которая отвечает за очищение поля ввода при нажатии на кнопку «=».

И последняя строка нашего кода — это «закрытие» окна tkinter.

Большое спасибо за прочтение данной публикации. Надеюсь она Вам была полезна.

Python | Простой графический калькулятор с использованием Tkinter

Python предлагает несколько вариантов разработки графического интерфейса пользователя. Из всех методов GUI tkinter является наиболее часто используемым методом. Это стандартный интерфейс Python для инструментария Tk GUI, поставляемый с Python. Python с tkinter выводит самый быстрый и простой способ создания приложений с графическим интерфейсом. Создание графического интерфейса с помощью tkinter — простая задача.

Чтобы создать ткинтер:

Давайте создадим простой калькулятор на основе графического интерфейса, используя модуль Python Tkinter, который может выполнять основные арифметические операции сложения, вычитания, умножения и деления.

Ниже приведена реализация:

# Python программа для создания простого графического интерфейса
# калькулятор с использованием Tkinter

# импортировать все из модуля tkinter

from tkinter import *

# глобально объявить переменную выражения

# Функция для обновления выражения
# в поле ввода текста

# указать глобальную переменную выражения

expression = expression + str (num)

# обновить выражение с помощью метода set

equation. set (expression)

# Функция для оценки финального выражения

# Попробуйте использовать оператор кроме

# для обработки ошибок как ноль

# ошибка деления и т. д.

# Поместите этот код в блок try

# которое может вызвать ошибку

# eval функция оценивает выражение

# и функция str конвертируют результат

total = str ( eval (expression))

equation. set (total)

# инициализировать переменную выражения

# если ошибка сгенерирована то обработай

equation. set ( » error » )

# Функция очистки содержимого
Количество текстового поля ввода

if __name__ = = «__main__» :

# создать окно с графическим интерфейсом

# установить цвет фона окна GUI

gui.configure(background = «light green» )

# установить заголовок окна GUI

gui.title( «Simple Calculator» )

# установить конфигурацию окна графического интерфейса

# StringVar () является классом переменной

# мы создаем экземпляр этого класса

# создать текстовое поле для ввода

expression_field = Entry(gui, textvariable = equation)

# метод сетки используется для размещения

# виджеты на соответствующих позициях

# в таблице как структура.

equation. set ( ‘enter your expression’ )

# создать кнопки и поместить в определенный

# расположение внутри корневого окна.

# когда пользователь нажимает кнопку, команда или

# Функция, связанная с этой кнопкой, выполняется.

# запустить графический интерфейс

Выход :
Как сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в pythonКак сделать калькулятор в python. Смотреть фото Как сделать калькулятор в python. Смотреть картинку Как сделать калькулятор в python. Картинка про Как сделать калькулятор в python. Фото Как сделать калькулятор в python

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *