1

As shown below, Function 1 calls another function (draw_text) so that I can display my output / result to a label within the canvas out my GUI. This all work great (thanks to Stack Overflow!!)

# Function 1

def Relay_1():
    arduinoData.write(b'1')
    draw_text(self, 'This is a Test')

# Function 2

def Relay_():
    arduinoData.write(b'1')
    draw_text(self, 'This is another test number 2')

#Function 3

def draw_text(self, text):
    self.canvas.create_text(340,330, anchor='center', text=text,
                            font=('Arial', '10', 'bold'))

Now my question:

How do I clear the "contents of the label" that has been created so each time I call Function 1 or 2, the result on the canvas will refresh / update. Currently the text message just overwrites itself.

martineau
  • 119,623
  • 25
  • 170
  • 301
John
  • 321
  • 5
  • 16

4 Answers4

2

Each time you create an object on a canvas, it returns an identifier. You can pass this identifier to the canvas delete method.

label_id = self.canvas.create_text(...)
...
self.canvas.delete(label_id)

You can also supply one or more tags to an item, and use the tag rather than the id:

self.canvas.create_text(..., tags=('label',))
...
self.canvas.delete('label')
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
2

For more details see How do we delete a shape that's already been created in Tkinter canvas?

from Tkinter import *


a = Tk()

canvas = Canvas(a, width = 500, height = 500)
canvas.pack()

myrect = canvas.create_rectangle(0,0,100,100)
canvas.delete(myrect) #Deletes the rectangle
martineau
  • 119,623
  • 25
  • 170
  • 301
john
  • 101
  • 1
  • 14
0

Clear all items from the canvas to start on a clean slate.

from Tkinter import ALL
...
self.canvas.delete(ALL)
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
0

I personally use this method:

You can create a variable which will be equal to canvas.create_text()

title = canvas.create_text(*needed_args, text='Something')

Then you can set the text to the empty string or change it by:

canvas.itemconfig(title, text='')

This method is especially useful for text replacement or temporary "deleting"