如何识别是否有文字?

How can I identify if there is text?

我想确定 tkinter 中 canvas 上是否有文本。

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")  

有人可以帮我吗?我必须找出是否有避免 UnboundLocal 错误的文本。

我期待着答案。谢谢!

如果 text 是全局的,您可以使用 if text not in globals() 检查是否定义了文本。此外,您可以使用 if globals().get('text') 如果 text 为空或未定义,它将 return False

text = ''

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

# False

您可以在函数中使用 locals() 执行相同的操作

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") 

如果您想从全局范围访问和更新 text 变量,请使用 global。如果 text 未在该范围内定义,您可以捕获引发的 NameError 异常。

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