Monday 13 April 2015

Creating a simple square root calculator

With the next code you will be able to use the input from the user an display the result in the created window by clicking a button with an assignated command.

# Calculating x**0.5
from Tkinter import *

def square_calc():
    x = x_val.get()
    sqx = x ** 0.5
    print "x =", x, "\t", x, "** 0.5 =", sqx
    sqx_txt = Label(root, text = "x ** 0.5 =").grid(row=3, column=0)
    sqx_lab = Label(root, text = sqx).grid(row=3, column=1)

root = Tk()
root.title("Calculating square root")

x_val = DoubleVar()

x_lab   = Label(root, text = "x").grid(row=0, column=0)
nmb     = Entry(root, textvariable = x_val).grid(row=0, column=1)
calc    = Button(root, text = "Calculate", command=square_calc).grid(columnspan=2)
y_lab   = Label(root, text = " ").grid(row=3, column=0)

root.mainloop()


The result would be like this:






Now you can try with a number



But there is a problem, if you put a number with an exact square root like '4', then the numeric result will get all mixed up with the previous answer.



The solution that I found out after searching here and there, even asking in Stack Overflow, is the next code:
from Tkinter import *

def square_calc():
    x = x_val.get()
    sqx = x ** 0.5
    sqx_txt = Label(root, text = "x ** 0.5 =").grid(row=3, column=0)
    sqx_lab.config(text=sqx)
    sqx_lab.grid(row=3, column=1, sticky=W)

root = Tk()
root.title("Calculating square root")

x_val = DoubleVar()

x_lab   = Label(root, text = "x").grid(row=0, column=0)
nmb     = Entry(root, textvariable = x_val).grid(row=0, column=1)
calc    = Button(root, text = "Calculate", command=square_calc).grid(columnspan=2)
y_lab   = Label(root, text = " ").grid(row=3, column=0)
sqx_lab = Label(root, text = " ")

root.mainloop()

Which gets rid of that little problem.




It seems necessary that I should mention the fact that I've been adviced about getting the habit of using classes, which means to use object oriented programmation in order to keep any wierd problem at bay, I suppose that's why got that 'bug' with my initial code.

No comments:

Post a Comment