Tkinter: What is faster: Deleting and drawing a new one or Itemconfig?

不问归期 提交于 2020-05-28 05:03:19

问题


On a Tkinter Canvas, what is faster on updating a piece of text, canvas.itemconfig(text, text='new text') or deleting the text and writing new text to the screen.

Deleting the text and adding new text:

text = canvas.create_text(200, 200, text='old text')
canvas.delete(text)
text = canvas.create_text(200, 200, text='old text')

Using itemconfig

text = canvas.create_text(200, 200, text='old text')
canvas.itemconfig(text, text='new text')

回答1:


Faster for one item is irrelevant. The canvas has performance problems1 when it has to manage large numbers of object ids, even if they are the ids of deleted items. Each time you delete and create the text, you are adding another id. If you delete and recreate a text item over and over, eventually you will cause performance problems.

The best solution is to configure the text of an existing item.

1 I can't cite a reference for this. I've looked around and can't find a definitive write-up, but I've seen this problem first-hand in the past.




回答2:


As for which is faster, well it really wont make much of a difference, since after all we're talking about fractions of seconds. You could say though that canvas.itemconfig is only one line of code, while deleting then re - adding text is 2 lines and 2 commands, so canvas.itemconfig might either make it faster or make your code more efficient. So... unless you're facing problems with canvas.itemconfig, I would stick to it for the time being.



来源:https://stackoverflow.com/questions/42352958/tkinter-what-is-faster-deleting-and-drawing-a-new-one-or-itemconfig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!