clearing text on canvas

D

devnew

hi
i am new to tkinter and would like some help with canvas

i am doing validation of contents of a folder and need to show the
ok/error messages on a canvas

resultdisplay =Canvas(...)
errmessage="error!"
okmessage="dir validation ok!"

if dirvalidate is False:
resultdisplay.create_text(1,50,anchor=W,text=errmessage,width=175)

else:
self.resultdisplay.create_text(1,50,anchor=W,text=okmessage,width=175)


my problem is that if validation succeeds or fails the text created on
canvas is displayed over the previous created text
I need to clear the previous text from the canvas before creating new
text
can someone help?
dn
 
P

Peter Otten

i am doing validation of contents of a folder and need to show the
ok/error messages on a canvas

resultdisplay =Canvas(...)
errmessage="error!"
okmessage="dir validation ok!"

if dirvalidate is False:

if ... is False: ...

is bad style. Just

if dirvalidate: ...

reads better and is less likely to cause subtle errors.
resultdisplay.create_text(1,50,anchor=W,text=errmessage,width=175)

else:
self.resultdisplay.create_text(1,50,anchor=W,text=okmessage,width=175)


my problem is that if validation succeeds or fails the text created on
canvas is displayed over the previous created text
I need to clear the previous text from the canvas before creating new
text
can someone help?

You create the text once but keep its handle for further changes.

handle = canvas.create_text(...)

You can change it later with

canvas.itemconfigure(handle, ...)

Here's a short self-contained example:

import Tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=100, height=100)
canvas.pack()

text_id = canvas.create_text(50, 50, width=100)

ok = False
def change_text():
global ok
ok = not ok
if ok:
text = "ok"
else:
text = "error"

canvas.itemconfigure(text_id, text=text)

button = tk.Button(root, text="change text", command=change_text)
button.pack()

root.mainloop()

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top