TechTorch

Location:HOME > Technology > content

Technology

Creating a GUI Calculator Using C and GTK: A Step-by-Step Guide

May 12, 2025Technology3148
Credit: Qwen, Developed by Alibaba Cloud Introduction This article pro

Credit: Qwen, Developed by Alibaba Cloud

Introduction

This article provides a detailed guide on creating a graphical user interface (GUI) calculator using the C programming language with the GTK (GIMP Toolkit) library. While C doesn't natively support GUI programming, GTK is a powerful and widely-used toolkit that simplifies the process. We will walk through the steps to build a basic calculator, explaining each part of the code along the way.

Prerequisites

Install GTK

Before proceeding, ensure that GTK is installed on your system. GTK can usually be installed via your package manager. On an Ubuntu system, you can use the following command:

sudo apt-get install libgtk-3-dev

Set Up Your Development Environment

Make sure you have a C compiler installed. gcc is commonly used for this purpose.

Basic Structure of a GTK Calculator

Let's delve into the creation of a simple calculator using GTK. We will create the source files and describe the necessary steps and code structure.

Step 1: Create the Source File

Create a file named calculator.c and write the following code:

#include gtk/gtk.hGtkWidget *entry;void on_button_clicked(GtkWidget *widget, gpointer data) {    const char *button_label  gtk_button_get_label(GTK_BUTTON(widget));    const char *current_text  gtk_entry_get_text(GTK_ENTRY(entry));    // Handle the equals button    if (g_strcmp0(button_label, "")  0) {        // Simple evaluation (not robust for demonstration only)        gdouble result  0;        gdouble value;        sscanf(current_text, "%lf", value);        // Here you would typically parse the expression and evaluate it        // For simplicity, we will just display the value back        gchar result_str[64];        snprintf(result_str, sizeof(result_str), "%lf", value);        gtk_entry_set_text(GTK_ENTRY(entry), result_str);    } else {        // Append the button label to the entry        gchar new_text[256];        g_snprintf(new_text, sizeof(new_text), "%s%s", current_text, button_label);        gtk_entry_set_text(GTK_ENTRY(entry), new_text);    }}int main(int argc, char *argv[]) {    gtk_init(argc, argv);    GtkWidget *window  gtk_window_new(GTK_WINDOW_TOPLEVEL);    gtk_window_set_title(GTK_WINDOW(window), "Calculator");    gtk_window_set_default_size(GTK_WINDOW(window), 300, 400);    g_signal_connect(window, "destroy", gtk_main_quit, NULL);    GtkWidget *grid  gtk_grid_new();    gtk_container_add(GTK_CONTAINER(window), grid);    entry  gtk_entry_new();    gtk_grid_attach(GTK_GRID(grid), entry, 0, 0, 4, 1);    const char *buttons[]  {        "7", "8", "9", "/",        "4", "5", "6", "*",        "1", "2", "3", "-",        "0", ".", "", " ",    };    for (int i  0; i  16; i  ) {        GtkWidget *button  gtk_button_new_with_label(buttons[i]);        g_signal_connect(button, "clicked", G_CALLBACK(on_button_clicked), entry);        gtk_grid_attach(GTK_GRID(grid), button, i % 4, 1   i / 4, 1, 1);    }    gtk_widget_show_all(window);    gtk_main();    return 0;}

Explanation of the Code

GTK Initialization

The program starts by initializing GTK and creating a main window.

Grid Layout

A grid layout is used to organize the buttons and entry field.

Entry Widget

An entry widget is created to display the current input.

Buttons

Buttons are created in a loop and connected to the on_button_clicked function, which handles button clicks.

Button Logic

The on_button_clicked function updates the entry field based on which button is pressed. It handles simple input and evaluates the expression when the equals button is pressed.

Note: This example provides a very basic calculator functionality, simply echoing the input. For a more advanced calculator, you would need to implement a proper expression parser and evaluator. Libraries such as can help with string manipulation and math functions.

Feel free to expand upon this code to add more features such as more complex calculations, error handling, or a more sophisticated user interface!

Key Takeaways:
- Install GTK using the package manager.
- Create a basic GUI using GTK widgets.
- Implement button handling with event callbacks.
- Showcase simple input handling and evaluation.
- Consider advanced features like expression parsing and error handling.

Conclusion

Creating a GUI calculator in C with GTK is an excellent exercise for understanding C programming and GUI event handling. By following the steps provided, you can build a functional calculator that can be extended further with additional features and polish.