Tkinter Initiation: Création d’une calculatrice en python

Posted by


Tkinter is a popular GUI library in Python that allows you to create graphical user interfaces for your programs. In this tutorial, we will be creating a simple calculator using Tkinter.

To get started, you will need to have Tkinter installed on your computer. Tkinter is included with Python by default, so you should already have it installed. If not, you can install it using the following command:

pip install tk

Now that you have Tkinter installed, let’s create our calculator. We will be using the following components:

  1. Entry widget for displaying the input and output
  2. Buttons for inputting numbers and operators
  3. Functions to perform calculations

First, let’s create a basic window for our calculator:

import tkinter as tk

root = tk.Tk()
root.title("Calculator")

entry = tk.Entry(root, width=20, borderwidth=5)
entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

root.mainloop()

This code will create a window with a single entry widget at the top. Now, let’s add buttons for numbers and operators:

def button_click(number):
    current = entry.get()
    entry.delete(0, tk.END)
    entry.insert(0, str(current) + str(number)

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    'C', '0', '=', '+'
]

row = 1
col = 0
for button in buttons:
    if button == 'C':
        tk.Button(root, text=button, width=5, command=lambda: entry.delete(0, tk.END)).grid(row=row, column=col)
    elif button == '=':
        tk.Button(root, text=button, width=5, command=lambda: entry.delete(0, tk.END)).grid(row=row, column=col)
    else:
        tk.Button(root, text=button, width=5, command=lambda b=button: button_click(b)).grid(row=row, column=col)

    col += 1
    if col > 3:
        col = 0
        row += 1

root.mainloop()

In this code, we’ve created a function button_click that updates the entry widget with the digits of the button pressed. We then create buttons for each digit, operator, and clear button. The buttons are organized in a 4×4 grid.

Next, let’s add the functionality to perform calculations:

def button_click(number):
    current = entry.get()
    entry.delete(0, tk.END)
    entry.insert(0, str(current) + str(number)

def clear():
    entry.delete(0, tk.END)

def calculate():
    try:
        result = eval(entry.get())
        entry.delete(0, tk.END)
        entry.insert(0, result)
    except:
        entry.delete(0, tk.END)
        entry.insert(0, "Error")

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    'C', '0', '=', '+'
]

row = 1
col = 0
for button in buttons:
    if button == 'C':
        tk.Button(root, text=button, width=5, command=clear).grid(row=row, column=col)
    elif button == '=':
        tk.Button(root, text=button, width=5, command=calculate).grid(row=row, column=col)
    else:
        tk.Button(root, text=button, width=5, command=lambda b=button: button_click(b)).grid(row=row, column=col)

    col += 1
    if col > 3:
        col = 0
        row += 1

root.mainloop()

In this final version of the code, we’ve added a function calculate that evaluates the expression in the entry widget. If an error occurs during calculation, an error message is displayed on the entry widget.

And there you have it! You have created a simple calculator using Tkinter in Python. Play around with the code and add more features to make your calculator more robust and user-friendly. Happy coding!

0 0 votes
Article Rating
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-lo5xo4jn1i
2 months ago

merci bcp ❤🎉

@yangmupafuyang6496
2 months ago

Merci pour cette mais comment
Afficher un resultat print dans un label tkinter python

@ilikethebanana9448
2 months ago

es ce que on peux crée une vrais calculatrice avec les script ?

@bak_ben3769
2 months ago

Merci pour la vidéo mais j'ai toujours du mal à exécuter certaines tâches pouvez vous m'aidez ??

@skateforlife3679
2 months ago

Super merci ! Je pense qu'on peut effectuer une boucle ou autre méthode pour éviter les copier collé des boutons ?

@ousmanegning3867
2 months ago

Bonjour professeur
Je voulais travailler sur un projet concernant le ramassage d’élèves
Avez vous un coup de pousse à me suggérer ?
Merci

@cafe-tomate
2 months ago

Bonjour, pourquoi indexez vous le btn1 à (2,1) alors que le texte occupe la zone (0,0), (0,1) (0,2) (0,3) et (0,4) ?

@ousmaneniang3107
2 months ago

toujrs claire

@momar8073
2 months ago

Thank u bro

@trotitac9749
2 months ago

J ai besoin de créer un projet qui permet d automatise des mesures on utilisant un port gpio (appareil utiliser gbf voltmetre ect…)

@hadnaneadeleke4055
2 months ago

Merci pour la vidéo

Elle est très explicite