Emefpe
Emefpe

Reputation: 13

How to pass calculation form Button command to Entry field?

I have two python scripts mainapp.py, and calculations.py

  1. mainapp.py
from tkinter import *
import calculations

root = Tk()

mainapp = Frame(root)
mainapp.grid()

label1 = Label(mainapp, text="Value A")
label1.grid(row=0, column=0)
value_a = IntVar()
entry1 = Entry(mainapp, textvariable=value_a)
entry1.grid(row=0, column=1)

label2 = Label(mainapp, text="Value B")
label2.grid(row=1, column=0)
value_b = IntVar()
entry2 = Entry(mainapp, textvariable=value_b)
entry2.grid(row=1, column=1)

button = Button(mainapp, text="Calculate",
                command=calculations.addvalues(a=value_a.get(), b=value_b.get()))
button.grid(row=2, columnspan=2)

label3 = Label(mainapp, text="A+B")
label3.grid(row=3, column=0)
value_c = IntVar()
entry3 = Entry(mainapp, textvariable=value_c)
entry3.grid(row=3, column=1)

root.mainloop()
  1. calculations.py

def addvalues(a, b): return a + b

I would like to pass the Button command calculation to entry3 field. How to do that?

Thank you for the help in advance.

Upvotes: 1

Views: 39

Answers (1)

Adam Brinded
Adam Brinded

Reputation: 89

you've done very well and are very close. It is often better to use a simple function (see foo() in my example) to manipulate entry boxes etc..

The entry3.delete(0, END) will ensure that the entry is clear (try it without this line and see what happens!)

from tkinter import *
import calculations


def foo():
    x = addvalues(a=value_a.get(), b=value_b.get())
    entry3.delete(0, END)
    entry3.insert(END, x)


root = Tk()

mainapp = Frame(root)
mainapp.grid()

label1 = Label(mainapp, text="Value A")
label1.grid(row=0, column=0)
value_a = IntVar()
entry1 = Entry(mainapp, textvariable=value_a)
entry1.grid(row=0, column=1)

label2 = Label(mainapp, text="Value B")
label2.grid(row=1, column=0)
value_b = IntVar()
entry2 = Entry(mainapp, textvariable=value_b)
entry2.grid(row=1, column=1)

button = Button(mainapp, text="Calculate",
                command=foo)
button.grid(row=2, columnspan=2)

label3 = Label(mainapp, text="A+B")
label3.grid(row=3, column=0)
value_c = IntVar()
entry3 = Entry(mainapp, textvariable=value_c)
entry3.grid(row=3, column=1)

root.mainloop()

Upvotes: 1

Related Questions