Tkinter – the button I made doesn't work

Question:

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.

Asked By: Hanul Jeon

||

Answers:

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))
                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Answered By: falsetru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.