2014-09-19 125 views
-1

假设我有一个画布,它具有某种背景,用tkinter形状绘制出来,最上面的是我正在移动一个圆圈。如何在不重绘每个元素的情况下更新画布?

是否有可能只重绘圆圈,而不是每次重画背景?

示例代码:

import Tkinter 

class gui(Tkinter.Tk): 

    def draw_background(self): 
     self.canvas.create_oval(0,0, 500, 500, fill = 'black') 

    def draw_circle(self,x, y): 
     self.canvas.create_oval(x,y, x+10,y+10, fill = 'green') 



    def __init__(self, parent): 
     Tkinter.Tk.__init__(self, parent) 
     self.guiHeight = 800 
     self.guiWidth = 800 
     self.initialise() 

    def animation(self): 

     self.x = self.x +1%100 
     self.y = self.y +1%100 

     self.canvas.delete("all") 
     self.draw_background()  
     self.draw_circle(self.x, self.y) 

     self.after(100,self.animation) 

    def initialise(self): 
     self.title('traffic') 

     self.canvas = Tkinter.Canvas(self, height = self.guiHeight, width = self.guiWidth) 
     self.draw_background()  
     self.canvas.pack() 

     self.x = 0 
     self.y = 0 
     self.after(100, self.animation) 
     self.mainloop() 


if __name__ == "__main__": 
    app = gui(None) 

该代码将实现正是我想要它做的。绿点向右下角移动,并将其自身显示在背景圆上。

但是,每次都告诉它重绘背景图像似乎很浪费(想象一下在绘制背景时是否涉及大量计算)是否可以在透明图层上显示,并重绘层?

回答

3

您可以使用move方法在画布上移动的任何项目。你也可以delete任何一个项目,并重画它。这些都不需要重绘任何其他对象。

当您创建一个项目,则返回一个ID,你可以给移动或删除方法。

self.circle_id = self.canvas.create_oval(x,y, x+10,y+10, fill = 'green') 
... 
# move the circle 10 pixels in the x and y directions 
self.canvas.move(self.circle_id, 10,10) 

你也可以给一个或多个元素标签(实际上,标签列表),然后在一个命令移动或删除所有与该标签的元素,以及:

self.canvas.create_oval(x, y, x+10, y+10, fill='green', tags=("circle",)) 
... 
self.canvas.move("circle", 10, 10) 

您也可以计算在圈中的所有新坐标,然后用coords方法更新:

# make the upper-left corner 0,0 and the lower right 100,100 
self.canvas.coords("circle", 0,0,100,100) 
相关问题