0

I am new to python and trying program for the following. I have a code snippet which outputs the label position to the shell. I wanted to hide the label or make them invisible. But still wanted to obtain the output, even if I click without seeing them.

I wrote some code, but it stays visible.

My coding:

import Tkinter
root = Tkinter.Tk()
def unshow_me(event):
    event.widget.grid_forget()

def handle_click(text):
    print text
    a=text
for r in range(3):
    for c in range(6):
        text = 'R=%s,C=%s'%(r,c)
        label = Tkinter.Label(root, text=text, borderwidth=1 )
        label.grid(row=r,column=c)
        label.bind("<Button-1>", lambda e, text=text:handle_click(text),unshow_me)


root.mainloop()

Please help me to rectify the problem!

matsjoyce
  • 5,744
  • 6
  • 31
  • 38
sar kite
  • 92
  • 1
  • 11

1 Answers1

2

As Bryan Oakley pointed out, you do not call unshow_me. However, unshow_me is not part of the lambda at all:

>>> def f():pass
... 
>>> def g():pass
... 
>>> lambda x: f(), g()
(<function <lambda> at 0x7f7737a267b8>, None)
>>> lambda x: (f(), g())
<function <lambda> at 0x7f7737a267b8>

The reason is that the lambda keyword has the lowest precedence in Python. Adding brackets to the lambda body, which includes the second function in your body, and calling unshow_me with the argument e makes your lambda:

lambda e, text=text:(handle_click(text), unshow_me(e))

Your complete program is then:

import Tkinter
root = Tkinter.Tk()
def unshow_me(event):
    event.widget.grid_forget()

def handle_click(text):
    print text
    a=text

for r in range(3):
    for c in range(6):
        text = 'R=%s,C=%s'%(r,c)
        label = Tkinter.Label(root, text=text, borderwidth=1 )
        label.grid(row=r,column=c)
        label.bind("<Button-1>", lambda e, text=text:(handle_click(text), unshow_me(e)))

root.mainloop()

Which produces the desired output (with several clicks):

enter image description here

However, it is worth noting that once hidden, the clicks will not be recorded, which is what the OP seems to want. If you want to find where the user clicks, try (modified from effbot):

import Tkinter
root = Tkinter.Tk()
def callback(event):
    print "clicked at", event.x, event.y

root.bind("<Button-1>", callback)
root.mainloop()
matsjoyce
  • 5,744
  • 6
  • 31
  • 38