0% found this document useful (0 votes)
429 views

Calculator in Go and Fyne

We have learned how to create a basic calculator app in Go and Fyne. The steps include: 1) Creating buttons for numbers, operations, and other functions like clear and back 2) Adding the buttons to the window using container boxes to layout them in rows and columns 3) Defining functions for each button to update the output label when clicked 4) Storing calculation history in an array and displaying it when the history button is clicked

Uploaded by

mamta yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
429 views

Calculator in Go and Fyne

We have learned how to create a basic calculator app in Go and Fyne. The steps include: 1) Creating buttons for numbers, operations, and other functions like clear and back 2) Adding the buttons to the window using container boxes to layout them in rows and columns 3) Defining functions for each button to update the output label when clicked 4) Storing calculation history in an array and displaying it when the history button is clicked

Uploaded by

mamta yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Calculator in Go and Fyne

Let’s get ready for some action now, shall we?

We have already learned how to write basic syntax in go language, i.e.


variable declaration, loops, functions, arrays, structures, etc. in our
previous videos. If you missed out on any of it, quickly go and check out
the following links:

For the YouTube video link of “Introduction To Go” - click here


For the YouTube video link of “Structures in Go” - click here

In one of the videos, we copy-pasted our snippet from fyne.io to


see how we can create our first app.
Let us have a quick look at our snippet:

In which we learn the following commands:

1) To create a new app - a := app.New()


2) Then we learnt how to open a new window by a particular
name, let's say “Hello” - w := a.NewWindow("Hello")
3) Our next step was to make a new label for our widget-
hello := widget.NewLabel("Hello Fyne!")
4) To make sure that our widget is in box shape we wrote the
following command -
w.SetContent(container.NewVBox()
5) Then we created a new button -
widget.NewButton("Hi!", func()
6) Then to set another text in our widget we used the command
i.e. hello.SetText("Welcome :)")
Earlier we all got to know about how to create your own app
widget, which looked somewhat like this:

(After Step 5 from our snippet)

Now to cross-check if our created app works fine, just click on the “Hi!”
symbol and see if the text “Hello Fyne !” changes to “Welcome :)”
! Now let us build our own calculator!

In this project we are going to build a calculator which will have


functionalities such as - History, Back, Clear, opening bracket “(”, closing
bracket “)”, division “/”, multiplication “*”, addition “+”, subtraction “-”,
equal to “=”, decimal point/dot “.”, and 0 - 9 decimal digits.
Here are the steps to build our calculator:

Our first step after creating the particular window from the above
snippet would be to create buttons for our calculator.

Syntax for creating button is


/*Name of button*/Btn:=widget.NewButton(/*"text to
be printed on button"*/, func(){})

For example, if we want to create a button for “History” then the


syntax would be as follows:

For creating a button for digit 4 our syntax will be:

Now it's your task to create all the buttons using similar syntax.

Now it's time to set our content inside our window, in short, we
need to show our buttons on our window.
Note: Whatever we write in our window is always treated as a row.

We’ll treat our buttons as one box, so now all of our buttons are part of
one box, inside that box, we’ll create another box that will contain
columns according to the buttons available in that particular row.
I.e.

Body of box -> Another Box containing two columns (History and Clear
button) -> another box containing 4 columns -> below that another box
containing 4 columns -> below that another box containing next 4
columns -> then our second last box containing 4 columns -> then our
last box containing 3 columns.
The layout we are talking about looks like this:

To create the boxes our syntax of code will look like this:

Similarly, we’ll create all the columns with the help of our similar syntax-
Change the name of your window accordingly.

Now we’ll take a variable named “output” and we’ll pass an empty string
in it. After that, we’ll take an “input” variable for our new label of the
widget and will pass the output in it.

After this, let’s figure out what will happen when we press the buttons,
i.e. let us move forward and see the functionality of our buttons:

Except “History”, “Clear” and “Equals to” buttons, all the functions will
have a similar type of syntax:
For example, whenever we click on our clear button, we want our output
to be an empty string. For that, we’ll keep out output as an empty string
and then set the output using.SetText inside the input variable.
Similarly, we’ll make changes for the rest of the buttons:

What do we want our back button to do?


Ans: We simply want it to reduce the length of our substring. I.e. if I have
a substring of length 5, then my back button should give me a substring
of length 4. That’s it. That’s our task!

We’ll only perform back operation when the length of our substring is
greater than zero. We’ll set out the output from “0 to length” and then
subtract 1 from it to reduce the substring.
In the end, well set out output text in our input variable.

The coding syntax for the same is as follows:


Moving forward to our equal to (“=”) function, now instead of banging our
head about syntaxial errors, we’ll simply take help from here.
First of all, we’ll type “go get” inside our console followed by the link that
has been given i.e. github.com/Knetic/govaluate, we’ll wait for a moment
then import the same library inside our program. Then we’ll copy-paste
our syntax for evaluable expression from here.

Now we’ll pass our output string inside our evaluable expression, Now if
my expression is evaluable then that expression should be my output,
otherwise, if it’s not evaluable then my output should print “Error”.

If I don’t have any error then I want my output to be equal to the “result”
value. The question that arises is-
“How do I convert the result value into a string?”

For that we have s special expression for you, add this expression
instead of the result and import the “strconv” inside our import function.
Which look as follows:

Now our final task is to write functionality for the “History Button”
Our first step would be creating an array then we’ll keep appending the
output in it.

When will “History” get created? Only after we perform equal to “=”
operation, right?
So let us make a few changes inside our equal to function. Firstly we’ll
store out output string value inside a new variable, let’s say ans and
then we’ll append the output expression with answer into our string.

Now we’ll append our strToAppend string inside our History array and
then we will set our output to our answer.

Whenever we click on our “History” button we want to remove the string


from the array and display it on our history.

Now inside our history function, we’ll run a reverse for loop because we
want to print the last string of operation as our recent most history.
Then well add the history array inside our history string.
And will print each operation on a new line.

After that, we’ll create a variable names “isHistory” and will initialize it to
a false value.

We’ll put a condition, which will empty the history string if clicked twice.
Outside our conditions, we’ll toggle the value of isHistory and then set
our history string.
In the end, our History function will look as follows:

Now if you want to resize your calculator prompt then use the following
command or the same, and adjust the final layout as per your own
convenience.

You can see that we have a different size dimension for equal to
button(“=”), for doing that we can use the following syntax:

That’s it. With these simple instructions and repetitive operations, we


were able to make our first project that too a “CALCULATOR” !!!
Complete Golang code to build a calculator:

package main

import (
"strconv"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
"github.com/Knetic/govaluate"
)

func main() {
a := app.New()
w := a.NewWindow("Calculator !")
w.Resize(fyne.NewSize(300,280))
output:= ""
input:= widget.NewLabel(output)
isHistory:=false;
historyStr:=""
history:=widget.NewLabel(historyStr)
var historyArr[]string;
historyBtn:=widget.NewButton("History", func() {
if isHistory{
historyStr = ""
}else{
for i:= len(historyArr)-1; i>=0;i--{
historyStr = historyStr+historyArr[i];
historyStr+="\n"
}
}
isHistory = !isHistory
history.SetText(historyStr);

})

backBtn:=widget.NewButton("Back", func() {
if len(output) > 0{
output = output[:len(output)-1];
input.SetText(output);}
})

clearBtn:=widget.NewButton("Clear", func() {
output = "";
input.SetText(output);
})

openBtn:=widget.NewButton("(", func() {
output = output+"(";
input.SetText(output);
})

closeBtn:=widget.NewButton(")", func() {
output = output+")";
input.SetText(output);
})

divideBtn:=widget.NewButton("/", func() {
output = output+"/";
input.SetText(output);
})

sevenBtn:=widget.NewButton("7", func() {
output = output+"7";
input.SetText(output);
})

eightBtn:=widget.NewButton("8", func() {
output = output+"8";
input.SetText(output);
})

nineBtn:=widget.NewButton("9", func() {
output = output+"9";
input.SetText(output);
})

multiplyBtn:=widget.NewButton("*", func() {
output = output+"*";
input.SetText(output);
})

fourBtn:=widget.NewButton("4", func() {
output = output+"4";
input.SetText(output);
})

fiveBtn:=widget.NewButton("5", func() {
output = output+"5";
input.SetText(output);
})

sixBtn:=widget.NewButton("6", func() {
output = output+"6";
input.SetText(output);
})

minusBtn:=widget.NewButton("-", func() {
output = output+"-";
input.SetText(output);
})

oneBtn:=widget.NewButton("1", func() {
output = output+"1";
input.SetText(output);
})
twoBtn:=widget.NewButton("2", func() {
output = output+"2";
input.SetText(output);
})

threeBtn:=widget.NewButton("3", func() {
output = output+"3";
input.SetText(output);
})

plusBtn:=widget.NewButton("+", func() {
output = output+"+";
input.SetText(output);
})

zeroBtn:=widget.NewButton("0", func() {
output = output+"0";
input.SetText(output);
})

dotBtn:=widget.NewButton(".", func() {
output = output+".";
input.SetText(output);
})

equalrBtn:=widget.NewButton("=", func() {

expression, err:=
govaluate.NewEvaluableExpression(output);
if err ==nil{
result, err := expression.Evaluate(nil);
if err==nil{
ans:= strconv.FormatFloat(result.(float64),'f', -1,
64);
strToAppend:=output+ "=" +ans;

historyArr = append(historyArr, strToAppend);


output = ans;
}else{
output= "Error";
}
}else{
output="Error";
}
input.SetText(output)

})

w.SetContent(container.NewVBox(
input,
history,

container.NewGridWithColumns(1,
container.NewGridWithColumns(2,
historyBtn,
backBtn),

container.NewGridWithColumns(4,
clearBtn,
openBtn,
closeBtn,
divideBtn),

container.NewGridWithColumns(4,
sevenBtn,
eightBtn,
nineBtn,
multiplyBtn),

container.NewGridWithColumns(4,
fourBtn,
fiveBtn,
sixBtn,
minusBtn),
container.NewGridWithColumns(4,
oneBtn,
twoBtn,
threeBtn,
plusBtn),

container.NewGridWithColumns(2,
container.NewGridWithColumns(2,
zeroBtn,
dotBtn,
),
equalrBtn),
),
))

w.ShowAndRun()
}

You can find the same article in lecture form on our youtube channel.

For the YouTube video link of “Calculator in Go and fyne” - click here
!!! We hope you found this article helpful !!!

For more free study resources and information about the courses, visit:

PepCoding | Online resources of data structure and advanced algorithms

You might also like