0

I have tried to make a following program: when opening the program, it shows an entry and a button labeled as '9'. Character '9' is added at the end of the entry when clicking the button '9'.

The code given below is I have written, but it doesn't work as I intended. The button doesn't work and the entry shows '09' rather than '0'.

# -*- coding : utf-8 -*-
import Tkinter as Tk
class calculator:
   def __init__(self, master):
       self.num = Tk.StringVar()
       self.opstate = None
       self.tempvar = 0

       # entry
       self.entry = Tk.Entry(root, textvariable = self.num, justify=Tk.RIGHT, width = 27)
       self.entry.pack(side = Tk.TOP)
       self.num.set("0")

       # Buttons
       self.numbuts = Tk.Frame(master)
       self.ins9 = Tk.Button(self.numbuts, text = "9", width = 3, command = self.fins(9))
       self.ins9.pack()

       self.numbuts.pack(side = Tk.LEFT)

   ##### Functions for Buttons #####
   def fins(self, x):
       self.entry.insert(Tk.END, str(x))

root = Tk.Tk()
calc = calculator(root)
root.mainloop()

I guess the part command = self.fins(9) is problematic but I don't know how to resolve it. Thanks for any help.

Hanul Jeon
  • 113
  • 3

1 Answers1

1

The code is passing the return value of the method call, not the method itself.

Pass a callback function using like following:

self.ins9 = Tk.Button(self.numbuts, text="9", width=3, command=lambda: self.fins(9))
                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Thanks for your answer, but I still not understand it because I may have no clear understand the basic concepts of OOP. Is there any good references to understand about OOP? (If possible, Korean books are prefered but it does not really matter.) – Hanul Jeon Jun 28 '15 at 09:01
  • @tetori, You need to pass a callback function, not a return value of the function call. It is not related to OOP. – falsetru Jun 28 '15 at 09:03