Делал калькулятор с помощью tkinter, но не понимаю как мне объединить почти полностью совпадающие функции plus
, minus
, um
, dell
в одну. Сама программа рабочая.
from tkinter import *
def is_digit(string):
if string.isdigit():
return True
else:
try:
float(string)
return True
except ValueError:
return False
def plus(key):
n1 = ent1.get().split()
n2 = ent2.get().split()
if not(is_digit(n1[0])==True and is_digit(n2[0])==True):
lbl["text"] = "Вводите только числа!!"
elif len(n1)>1 or len(n2)>1:
lbl["text"] = "Вводите только одно число в строке!"
elif key == "+":
s = float(n1[0]) + float(n2[0])
lbl["text"] = s
def minus():
n1 = ent1.get().split()
n2 = ent2.get().split()
if not(is_digit(n1[0])==True and is_digit(n2[0])==True):
lbl["text"] = "Вводите только числа!!"
elif len(n1)>1 or len(n2)>1:
lbl["text"] = "Вводите только одно число в строке!"
else:
s = float(n1[0]) - float(n2[0])
lbl["text"] = s
def um():
n1 = ent1.get().split()
n2 = ent2.get().split()
if not(is_digit(n1[0])==True and is_digit(n2[0])==True):
lbl["text"] = "Вводите только числа!!"
elif len(n1)>1 or len(n2)>1:
lbl["text"] = "Вводите только одно число в строке!"
else:
s = float(n1[0]) * float(n2[0])
lbl["text"] = s
def dell():
n1 = ent1.get().split()
n2 = ent2.get().split()
if not(is_digit(n1[0])==True and is_digit(n2[0])==True):
lbl["text"] = "Вводите только числа!!"
elif len(n1)>1 or len(n2)>1:
lbl["text"] = "Вводите только одно число в строке!"
else:
if float(n2[0])==0:
lbl["text"] = "На ноль делить нельзя"
else:
s = float(n1[0])/float(n2[0])
lbl["text"] = s
root = Tk()
ent1 = Entry(root, width = 30)
ent2 = Entry(root, width = 30)
btnp = Button(root, text = "+", command = plus, width = 20)
btnm = Button(root, text = "-", command = minus, width = 20)
btnu = Button(root, text = "*", command = um, width = 20)
btnd = Button(root, text = "/", command = dell, width = 20)
lbl = Label(root, width = 30)
ent1.pack()
ent2.pack()
lbl.pack()
btnp.pack()
btnm.pack()
btnu.pack()
btnd.pack()
root.mainloop()