2

I am trying to make a calculator with the help of tkinter. I have defined a function click, which returns the value the user clicked but it is giving a error which I am not understanding.

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python39\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
TypeError: click() missing 1 required positional argument: 'event'

My code is as follows:

from tkinter import *

def click(event):
    text = event.widget.cget("text")

icon = r"C:\Users\Sumit\vs code python\projects\tkinter_course\calculator.ico"
root = Tk()
root.configure(bg = "black")

root.geometry("644x500")
root.title("Calculator by Arnav")
root.wm_iconbitmap(icon)

scvalue = StringVar()
scvalue.set("")
screen = Entry(root, textvar=scvalue, font="lucida 37 bold")
screen.pack(fill=X, ipadx=8, pady=10, padx=12)
    
f1 = Frame(root, bg = 'white' ).pack(side = LEFT)

b1 = Button(f1 , text = "1", font = 'lucida 35 bold',command=click).pack(anchor = 'nw',side = 
LEFT, padx = 23)


b2 = Button(f1 , text = "2", font = 'lucida 35 bold',command=click).pack(anchor = 'nw',side = 
LEFT, padx = 23)


b3 = Button(f1 , text = "3", font = 'lucida 35 bold',command=click).pack(anchor = 'nw',side = 
LEFT, padx = 23)

root.mainloop()

It is telling that I have not defined event, but I have. Pls help.

  • 1
    `event` is only passed when you `bind` the widgets. And it is passed _implicitly_ by tkinter. – Delrius Euphoria Jan 17 '22 at 10:53
  • so how do I do it?\ –  Jan 17 '22 at 10:54
  • Why do you need `event`? – Delrius Euphoria Jan 17 '22 at 10:55
  • 1
    to get the text of button when clicked –  Jan 17 '22 at 10:57
  • You don't need `event` for that, you can define `b2` such that it is not `None` and then `print(b2['text'])` to get the text – Delrius Euphoria Jan 17 '22 at 10:57
  • Exception in Tkinter callback Traceback (most recent call last): File "C:\Python39\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "c:\Users\Sumit\vs code python\projects\tkinter_course\calculator.py", line 4, in click print(b2['text']) TypeError: 'NoneType' object is not subscriptable –  Jan 17 '22 at 10:59
  • this error is coming –  Jan 17 '22 at 11:00
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/241138/discussion-between-arnav-tripathi-and-cool-cloud). –  Jan 17 '22 at 11:00
  • I told you to make it such that it is not `None`, follow: https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-attribute-name – Delrius Euphoria Jan 17 '22 at 11:02
  • 2
    thanks i got it –  Jan 17 '22 at 11:05

1 Answers1

1

You need to bind your function to the widget you want to detect with this line of code...

<Button-Variable-Name-Here>.bind("<Button-1>", click)

This will then check if the widget is ever clicked with the left mouse button.

TheEngineerGuy
  • 208
  • 2
  • 8