-1

I am a very very very beginner with programming languages, and now I started learning python, for basic I have learned it and now I just started trying to make something like a simple calculator with a Tkinter. here I am trying to make a simple calculator with 'Entry' and 'Button', but I have difficulty with what to expect. what I want in my application is: how to combine or add values from the first and second entry fields with the button in question (+), then after the button is clicked the results appear in the box entry next to the (+) button. I know that there have been many questions here with similar questions (Entry widgets etc) but I am really a beginner and have not gotten any answers by looking at the questions that were already in this forum. sorry for this beginner question, and I beg for your help.

import tkinter as tk
from tkinter import *

root = tk.Tk() #main windownya
root.geometry("300x300")
root.title("Little Calc")  

#Label
Label(root, text="Input First Number: ").grid(row=0, column=0)
Label(root, text="Input Second Number:     ").grid(row=1, column=0)
Label(root, text="Choose Addition: ").grid(row=2, column=0)
Label(root, text="Result: ").grid(row=2, column=1)


#Entry
firstnumb = Entry(textvariable=IntVar()).grid(row=0, column=1)
secnumb = Entry(textvariable=IntVar()).grid(row=1, column=1)


#Plus Button
plus_button = Button(root, text="+", command=lambda: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0)
plusresult = Entry(plus_button).grid(row=3, column=1)


root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

When I run your code, I get a nullPointerException here:

plus_button = Button(root, text="+", command=lambda: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0)

Why does this happen? You use the get() method on firstnumb and secnumb, those variables are defines as:

firstnumb = Entry(textvariable=IntVar()).grid(row=0, column=1) 
secnumb = Entry(textvariable=IntVar()).grid(row=1, column=1)

And both these variables have null as value instead of the Entry object that you would want. This happens because you also use the grid() method in your variable declaration and this method returns null. Doing this in two steps fixes your problem.

firstnumb = Entry(textvariable=IntVar())
firstnumb.grid(row=0, column=1)
secnumb = Entry(textvariable=IntVar())
secnumb.grid(row=1, column=1)

When I now click the "+" button no error occurs but the result is also not yet displayed. I advise you to make a new function where you put this code: firstnumb.get()+secnumb.get(), width=6, height=1).grid(row=3, column=0 and the code to display the result. Also, note that get() will return a string, make sure you first cast it to an int or float before adding both values. If you don't do that, 10 + 15 will give 1015.

debsim
  • 582
  • 4
  • 19