使用Tkinter绘制一个矩形?

时间:2017-02-22 02:56:12

标签: python tkinter tkinter-canvas

到目前为止我有这个代码。起初我画了一些效果很好的圆圈。我认为绘制矩形会很容易,但我只能绘制正方形。我希望有各种宽度和长度的形状。我知道我需要更改(x1,y1,x2,y2)的方框,但我该怎么做呢。

def down(event): # A mouse event will be passed in with x and y attributes
global startx, starty # Use global variables for assignment
startx = event.x # Store the mouse down coordinates in the global variables
starty = event.y

def up(event):
    tk_color_string = color(red_intvar, green_intvar, blue_intvar)
    r = (startx-event.x)**2 + (starty-event.y)**2  # Pythagorean theorem
    r = int(r**.5)                                 # square root to get distance
    new_shape = canvas.create_rectangle(startx-r, starty-r, startx+r, starty+r,
                                     fill=tk_color_string, outline='#000000')
    shapes.append(new_shape) # aggregate the canvas' item

整个代码超过100行,所以我希望这篇文章有助于展示我的要求。enter image description here

1 个答案:

答案 0 :(得分:2)

我提供了一个示例代码,我刚才写了如何使用鼠标在tkinter canvas中创建矩形。我希望这有助于您了解所需的相关程序和方法。此后,根据您的特定问题进行调整。希望这有助于您和最好的问候。

示例代码:如何创建允许用户使用鼠标绘制矩形对象的tkinter画布。

import tkinter as tk

class App(tk.Frame):
    def __init__( self, parent):
        tk.Frame.__init__(self, parent)
        self._createVariables(parent)
        self._createCanvas()
        self._createCanvasBinding()

    def _createVariables(self, parent):
        self.parent = parent
        self.rectx0 = 0
        self.recty0 = 0
        self.rectx1 = 0
        self.recty1 = 0
        self.rectid = None

    def _createCanvas(self):
        self.canvas = tk.Canvas(self.parent, width = 800, height = 400,
                                bg = "white" )
        self.canvas.grid(row=0, column=0, sticky='nsew')

    def _createCanvasBinding(self):
        self.canvas.bind( "<Button-1>", self.startRect )
        self.canvas.bind( "<ButtonRelease-1>", self.stopRect )
        self.canvas.bind( "<B1-Motion>", self.movingRect )

    def startRect(self, event):
        #Translate mouse screen x0,y0 coordinates to canvas coordinates
        self.rectx0 = self.canvas.canvasx(event.x)
        self.recty0 = self.canvas.canvasy(event.y) 
        #Create rectangle
        self.rectid = self.canvas.create_rectangle(
            self.rectx0, self.recty0, self.rectx0, self.recty0, fill="#4eccde")
        print('Rectangle {0} started at {1} {2} {3} {4} '.
              format(self.rectid, self.rectx0, self.recty0, self.rectx0,
                     self.recty0))

    def movingRect(self, event):
        #Translate mouse screen x1,y1 coordinates to canvas coordinates
        self.rectx1 = self.canvas.canvasx(event.x)
        self.recty1 = self.canvas.canvasy(event.y)
        #Modify rectangle x1, y1 coordinates
        self.canvas.coords(self.rectid, self.rectx0, self.recty0,
                      self.rectx1, self.recty1)
        print('Rectangle x1, y1 = ', self.rectx1, self.recty1)

    def stopRect(self, event):
        #Translate mouse screen x1,y1 coordinates to canvas coordinates
        self.rectx1 = self.canvas.canvasx(event.x)
        self.recty1 = self.canvas.canvasy(event.y)
        #Modify rectangle x1, y1 coordinates
        self.canvas.coords(self.rectid, self.rectx0, self.recty0,
                      self.rectx1, self.recty1)
        print('Rectangle ended')


if __name__ == "__main__":
    root = tk.Tk()
    root.geometry( "600x400" )
    app = App(root)
    root.mainloop()

使用的步骤和方法概述:

  1. 使用Tk()方法
  2. tk.Canvas()窗口中创建画布小部件
  3. 将鼠标事件<Button-1><ButtonRelease-1><B1-Motion>tk.Canvas小部件的回调绑定。
  4. 对于以下每个事件:
    3.1使用方法.canvasx(event.x).canvasy(event.y)将鼠标指针屏幕x,y坐标转换为画布坐标,并将这些转换后的corrdinate存储在变量self.rectx0self.recty0self.rectx1中, self.recty1event.xevent.y提供鼠标指针屏幕坐标。
    3.2使用canvas方法.create_rectangle(x0, y0, x1, y1, option, ...)创建矩形或使用canvas方法.coords(tagOrId, x0, y0, x1, y1)修改矩形坐标。这里,x0y0x1y1表示矩形对象的左上角和右下角x&amp; y画布坐标,tagOrId表示矩形对象ID。
    3.3仅对于<Button-1>,需要将创建的矩形对象的ID存储在变量中。只要在.coords() method<B1-Motion>期间调用<ButtonRelease-1>,此变量就会为tagOrId提供值。