|
| 1 | +import tkinter as tk |
| 2 | + |
| 3 | +digit = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] |
| 4 | +denominations = ["", "Thousand", "Million", "Billion", "Trillion"] |
| 5 | +tens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] |
| 6 | +ties = ["Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"] |
| 7 | + |
| 8 | +def convertNumberToWords(): |
| 9 | + inputValue = numberEntry.get() |
| 10 | + |
| 11 | + if not inputValue.isdigit(): |
| 12 | + resultLabel.config(text="Invalid Entered Value", fg="red") |
| 13 | + |
| 14 | + elif len(inputValue) > 15: |
| 15 | + resultLabel.config(text="Entered number is too large", fg="yellow") |
| 16 | + |
| 17 | + else: |
| 18 | + |
| 19 | + while len(inputValue) % 3 != 0: |
| 20 | + inputValue = "0" + inputValue |
| 21 | + |
| 22 | + inputValue = inputValue[::-1] |
| 23 | + |
| 24 | + def add(s1, s2): |
| 25 | + if s1 and s2: |
| 26 | + return s1 + " " + s2 |
| 27 | + return s1 + s2 |
| 28 | + |
| 29 | + def convert(index, level): |
| 30 | + if index >= len(inputValue): |
| 31 | + return "" |
| 32 | + |
| 33 | + cur = "" |
| 34 | + od = int(inputValue[index]) |
| 35 | + td = int(inputValue[index + 1]) |
| 36 | + hd = int(inputValue[index + 2]) |
| 37 | + |
| 38 | + if hd: |
| 39 | + cur = add(cur, add(digit[hd], "Hundred")) |
| 40 | + |
| 41 | + if td: |
| 42 | + if td == 1: |
| 43 | + cur = add(cur, tens[od]) |
| 44 | + else: |
| 45 | + cur = add(cur, ties[td - 1]) |
| 46 | + if od: |
| 47 | + cur = add(cur, digit[od]) |
| 48 | + elif od: |
| 49 | + cur = add(cur, digit[od]) |
| 50 | + |
| 51 | + if cur: |
| 52 | + cur = add(cur, denominations[level]) |
| 53 | + |
| 54 | + return add(convert(index + 3, level + 1), cur) |
| 55 | + |
| 56 | + result = "Zero" if inputValue == "000" else convert(0, 0) |
| 57 | + resultLabel.config(text=result, fg="white") |
| 58 | + |
| 59 | +window = tk.Tk() |
| 60 | +window.title("Number to Words Converter") |
| 61 | +window.configure(background="black") |
| 62 | + |
| 63 | +numberLabel = tk.Label(window, text="Enter Number:", bg="black", fg="white") |
| 64 | +numberEntry = tk.Entry(window) |
| 65 | +resultLabel = tk.Label(window, text="In Words:", bg="black", fg="white") |
| 66 | +convertButton = tk.Button(window, text="Convert", command=convertNumberToWords) |
| 67 | + |
| 68 | +numberLabel.grid(row=0, column=0, padx=10, pady=10) |
| 69 | +numberEntry.grid(row=0, column=1, padx=10, pady=10) |
| 70 | +convertButton.grid(row=1, column=0, columnspan=2, padx=10, pady=10) |
| 71 | +resultLabel.grid(row=2, column=0, padx=10, pady=10, columnspan=2) |
| 72 | + |
| 73 | +window.mainloop() |
0 commit comments