Amazing-Python-Scripts

Форк
0
180 строк · 5.1 Кб
1
from tkinter import *
2

3

4
def SetStatusError():
5
    """ Sets Status bar label to error message """
6
    Status["text"] = "Wronge Input(s)... :\ "
7
    Status["fg"] = "red"
8

9

10
def Con_Base_X_to_Dec(num, base_x):
11
    # Converting the integeral part
12
    # Extract integerals in reverse order
13
    integeral_part = str(int(num))[::-1]
14
    i = 0
15
    res = 0
16
    for number in integeral_part:
17
        # Convert each number to decimal
18
        element = int(number) * (base_x**i)
19
        # Add element to result
20
        res += element
21
        i += 1
22

23
    # Converting the decimal part
24
    decimal_part = str(num)
25
    # Extract decimal part using string manipulation
26
    decimal_part = decimal_part[decimal_part.index(".")+1:]
27
    i = -1
28
    for decimal in decimal_part:
29
        # Convert each number to decimal
30
        element = int(decimal) * (base_x**i)
31
        # Add element to result
32
        res += element
33
        i += -1
34

35
    # Return total result
36
    return res
37

38

39
def Con_Dec_to_Base_Y(num, base_y):
40
    # Converting the integeral part
41
    integeral_part = int(num)
42
    res_int = []
43
    while int(integeral_part) != 0:
44
        integeral_part = integeral_part / base_y                    # Divide number by base
45
        element = (integeral_part - int(integeral_part)) * \
46
            base_y   # Get the remainder
47
        # Append element
48
        res_int.append(str(int(element)))
49
    # Numbers are organised from LCM to HCM
50
    res_int = res_int[::-1]
51

52
    # Converting the decimal part
53
    decimal_part = num - int(num)
54
    res_dec = []
55
    while (decimal_part != 0):
56
        decimal_part = (decimal_part - int(decimal_part)) * \
57
            base_y  # Multiply decimal part by base
58
        # Check if not duplicated, for no infinite loops
59
        if str(int(decimal_part)) in res_dec:
60
            break
61
        # Append element
62
        res_dec.append(str(int(decimal_part)))
63

64
    # Organize result
65
    if len(res_dec) == 0:
66
        # If result has decimal numbers
67
        res = res_int
68
    else:
69
        res = res_int + ["."] + res_dec                             # If not
70

71
    # Return grouped result
72
    return " ".join(res)
73

74

75
def Main():
76
    """ Function to validate entry fields """
77
    # <----- Validation ----->
78
    # Validate Number
79
    num = Num_Val.get()
80
    try:
81
        num = float(num)
82
    except:
83
        Num.focus()
84
        SetStatusError()
85
        return
86
    # Validate Base X
87
    base_x = Base_X_Val.get()
88
    try:
89
        base_x = int(base_x)
90
    except:
91
        Base_X.focus()
92
        SetStatusError()
93
        return
94
    # Validate Base X
95
    base_y = Base_Y_Val.get()
96
    try:
97
        base_y = int(base_y)
98
    except:
99
        Base_Y.focus()
100
        SetStatusError()
101
        return
102
    # If same bases are entered
103
    if base_x == base_y or base_x < 2 or base_y < 2:
104
        Status["text"] = "Huh?! -_- "
105
        Status["fg"] = "orange"
106
        return
107
    # <----- check base x value ----->
108
    if base_x == 10:
109
        Result = Con_Dec_to_Base_Y(num, base_y)
110
    if base_y == 10:
111
        Result = Con_Base_X_to_Dec(num, base_x)
112
    else:
113
        Result = Con_Base_X_to_Dec(num, base_x)
114
        Result = Con_Dec_to_Base_Y(Result, base_y)
115

116
    Status["text"] = "Successfull Conversion! :0 "
117
    Status["fg"] = "green"
118
    Result_Entry_Val.set(Result)
119

120

121
# <----- GUI Code Beginning ----->
122
main_window = Tk()
123
main_window.title("Base-N Calculator")
124
Icon = PhotoImage(file="./Base-N_Calc/data/GSSOC.png")
125
main_window.iconphoto(False, Icon)
126
main_window.geometry("420x250")
127

128

129
# <----- Elements for number that is going to be converted ----->
130
Num_Label = Label(main_window, text="Enter Number :",
131
                  anchor=E, font=("Calibri", 9))
132
Num_Label.place(x=30, y=30)
133
Num_Val = StringVar()
134
Num = Entry(main_window, textvariable=Num_Val, font=("Calibri", 9))
135
Num.place(x=120, y=32)
136

137

138
# <----- Elements for Base-X ----->
139
Base_X_Label = Label(main_window, text="Base-X :",
140
                     anchor=E, font=("Calibri", 9))
141
Base_X_Label.place(x=250, y=30)
142
Base_X_Val = StringVar()
143
Base_X = Entry(main_window, textvariable=Base_X_Val, font=("Calibri", 9))
144
Base_X.place(x=305, y=32, width=30)
145

146

147
# <----- Elements for Base-Y ----->
148
Base_Y_Label = Label(main_window, text="Base-Y :",
149
                     anchor=E, font=("Calibri", 9))
150
Base_Y_Label.place(x=250, y=50)
151
Base_Y_Val = StringVar()
152
Base_Y = Entry(main_window, textvariable=Base_Y_Val, font=("Calibri", 9))
153
Base_Y.place(x=305, y=52, width=30)
154

155

156
# <----- Elements for calculate button ----->
157
Calculate_Button = Button(main_window, text="Convert",
158
                          font=("Calibri", 9), command=Main)
159
Calculate_Button.place(x=180, y=75, width=80)
160

161

162
# <----- Elements for Result ----->
163
Result_Label = Label(main_window, text="Result :",
164
                     anchor=E, font=("Calibri", 9))
165
Result_Label.place(x=100, y=130)
166
Result_Entry_Val = StringVar()
167
Result_Entry = Entry(
168
    main_window, textvariable=Result_Entry_Val, font=("Calibri", 9))
169
Result_Entry.configure(state='readonly')
170
Result_Entry.place(x=150, y=130)
171

172

173
# <----- Elements for Status Bar ----->
174
Status = Label(main_window, text="Hello!! :D", fg="green", font=(
175
    "Calibri", 9), bd=1, relief=SUNKEN, anchor=W, padx=3)
176
Status.pack(side=BOTTOM, fill=X)
177

178

179
# <----- Load Main Window ----->
180
main_window.mainloop()
181

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.