DEV Community

Cover image for Create a Simple Decimal to Binary Converter With Python
Hazrat Ali
Hazrat Ali

Posted on

Create a Simple Decimal to Binary Converter With Python

In this particular article, we look into how we can create a graphical user interface for converting a decimal number into binary with the help of the Tkinter Python library. Although we can convert a decimal number to binary in many ways in this particular case we will use the Python Numpy Library to convert a Decimal value to a binary value for error handling.
The Complete article for the Decimal to Binary Converter with Python.

from tkinter import *
from tkinter import ttk
from numpy import binary_repr

def decimal_2_bin(*args):
        value = int(decimal.get())
        binary.set(binary_repr(value, None))
    except ValueError:
root = Tk()
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
decimal = StringVar()
decimal_entry = ttk.Entry(mainframe, width=7, textvariable=decimal)
decimal_entry.grid(column=2, row=1, sticky=(W, E))
binary = StringVar()
ttk.Label(mainframe, textvariable=binary).grid(column=2, row=2, sticky=(W, E))
ttk.Button(mainframe, text="Calculate", command=decimal_2_bin).grid(column=3, row=3, sticky=W)
ttk.Label(mainframe, text="in Decimal").grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text="Binary").grid(column=3, row=2, sticky=W)
for child in mainframe.winfo_children():
    child.grid_configure(padx=5, pady=5)

root.bind("<Return>", decimal_2_bin)
Enter fullscreen mode Exit fullscreen mode

If you have any questions please let me know in the comment section.

Discussion (0)