在画布中逻辑放大/缩小

时间:2013-10-30 08:08:29

标签: python-2.7 canvas tkinter

我想创建一个画布小部件,允许用户在其上绘图。我正在使用canvas.bind。我想要的是画布的大小原本应该是32x32,但是当它显示时,它应该像原始小部件的缩放版本,而不需要调整原始画布的大小。我必须使用较小的尺寸(32x32)进一步处理绘制的图片。这意味着如果画布大小为32x32,那么它应该显示为512x512大小以用于绘图目的,但是32x32大小用于处理目的。我尝试使用canvas.Scale,但似乎它对此目的没有帮助,因为它调整了原始小部件的大小。有人可以指导我吗?我使用python2.7。

谢谢!

1 个答案:

答案 0 :(得分:2)

如果我完全理解你的问题,那么我认为这将是你的解决方案:

enter image description here

from __future__ import division
import Tkinter

ORIGINAL_WIDTH  = 32
ORIGINAL_HEIGHT = 32
WINDOW_WIDTH  = 512
WINDOW_HEIGHT = 512
WIDTH_RATIO  = WINDOW_WIDTH/ORIGINAL_WIDTH
HEIGHT_RATIO = WINDOW_HEIGHT/ORIGINAL_HEIGHT

class App(Tkinter.Tk):

    def __init__(self, *args, **kwargs):
        Tkinter.Tk.__init__(self, *args, **kwargs)
        self.canvas = canvas = Tkinter.Canvas( self,
                                               highlightthickness = 0,
                                               width  = WINDOW_WIDTH,
                                               height = WINDOW_HEIGHT )
        self.canvas.pack()
        # Create a list for holding canvas objects
        self.scene = []
        # Draw objects and scale them
        self.draw()
        self.zoom()


    def draw(self):
        canvas = self.canvas

        # Draw rectangles within the range of 0..32 x 0..32
        rect1 = canvas.create_rectangle(  2,  0, 30,  2, fill='black' )
        rect2 = canvas.create_rectangle(  0,  2,  2, 30, fill='black' )
        rect3 = canvas.create_rectangle( 30,  2, 32, 30, fill='black' )
        rect4 = canvas.create_rectangle(  2, 30, 30, 32, fill='black' )
        rect5 = canvas.create_rectangle( 10, 10, 22, 22, fill='black' )

        self.scene.extend( (rect1, rect2, rect3, rect4, rect5) )

    def zoom(self):
        canvas = self.canvas
        # Scale all objects on scene
        for item in self.scene:
            canvas.scale( item, 0, 0, WIDTH_RATIO, HEIGHT_RATIO )

App().mainloop()