Timmy
Timmy

Reputation: 125

How can I identify if there is text?

I want to identify if there is text on canvas in tkinter.

import tkinter  
c = tkinter.Canvas(width=500, height=500)  
def actionOne():  
      c.delete(text)                          #here I have to identify if there is any text  
      text = c.create_text(250, 400, text="Hi")  
def actionTwo():  
      c.delete(text)                     # Here again
      c.create_text(250, 400, text="Bye")  

Can anybody help me please? I have to find out if there is text to avoid an UnboundLocal Error.

I am looking forward for answers. Thanks!

Upvotes: 3

Views: 207

Answers (2)

Olivier Melançon
Olivier Melançon

Reputation: 22324

If you want to access and update the text variable from the global scope, do so with global. If text is not defined in that scope, you can catch the NameError exception raised.

def actionOne():
    global text
    try:
        c.delete(text)
    except NameError:
        pass
        text = c.create_text(250, 400, text="Hi")

Upvotes: 3

C.Nivs
C.Nivs

Reputation: 13106

If text is global, you can use if text not in globals() to check if text is defined. Furthermore, you can use if globals().get('text') which will return False if text is either empty or not defined:

text = ''

if not globals().get('text'):
    print(False)

# False

You can do the same thing with locals() inside a function

def actionOne():
  if isinstance(locals().get('text'), str()) and len(locals().get('text'))>1:  
      c.delete(text)                            
  text = c.create_text(250, 400, text="Hi") 

Upvotes: 2

Related Questions