当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.create_polygon方法代码示例

本文整理汇总了Python中tkinter.Canvas.create_polygon方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_polygon方法的具体用法?Python Canvas.create_polygon怎么用?Python Canvas.create_polygon使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.Canvas的用法示例。


在下文中一共展示了Canvas.create_polygon方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
def main():
    from tkinter import Canvas, mainloop, Tk
    gamma, size = [0.3, 0.2, -0.1, -0.4, 0.0], 11
    width, height, scale, center = 800, 800, 20, 400+400j
    w = Canvas(Tk(), width=width, height=height)
    w.pack()
    for rhombus, color in tiling(gamma, size):
        coords = to_canvas(rhombus, scale, center)
        w.create_polygon(*coords, fill=color, outline="black")
    mainloop()
开发者ID:mdickinson,项目名称:pentagrid,代码行数:12,代码来源:pentagrid.py

示例2: demo1

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
def demo1():
    try:
        
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas, PhotoImage, NW, SW
        else:
            from Tkinter import Tk, Canvas, PhotoImage, NW, SW
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        
        contour = [(491.1025968497233, 19.886736214605065), (491.1025968497233, 5.524093392945851), (455.34269902086, 5.524093392945851), (455.34269902086, 19.886736214605065), (353.68241805023416, 17.677098857426728), (353.68241805023416, 8.838549428713364), (323.20136228182207, 8.838549428713364), (323.20136228182207, 17.677098857426728), (210.81311196253725, 14.362642821659207), (210.81311196253725, 3.3144560357675132), (175.05321413367392, 3.3144560357675132), (175.05321413367392, 14.362642821659207), (73.22264793529162, 14.362642821659207), (73.22264793529162, 10.0), (34.05704555129843, 10.0), (32.18390804597701, 110.48186785891704), (10.0, 110.48186785891704), (10.0, 162.40834575260803), (48.36100468284376, 156.88425235966218), (75.09578544061303, 156.88425235966218), (128.56534695615156, 162.40834575260803), (178.62920391656024, 176.77098857426725), (226.81992337164752, 196.65772478887232), (249.9787143465304, 211.02036761053148), (291.18773946360153, 246.374565325385), (328.65048957002983, 283.9384003974168), (337.5053214133674, 298.30104321907595), (337.5053214133674, 341.3889716840536), (448.1907194550873, 350.22752111276696), (448.1907194550873, 333.6552409339294), (685.7386121753938, 350.22752111276696), (683.8654746700724, 356.856433184302), (771.3920817369094, 364.5901639344262), (774.9680715197957, 318.18777943368104), (767.816091954023, 318.18777943368104), (789.272030651341, 60.765027322404364), (796.4240102171137, 60.765027322404364), (800.0, 8.838549428713364), (757.088122605364, 8.838549428713364), (757.088122605364, 23.20119225037257), (644.6998722860792, 19.886736214605065), (644.6998722860792, 8.838549428713364), (610.8131119625373, 5.524093392945851), (608.9399744572158, 19.886736214605065)]
        holea = [(162.62239250744997, 127.0541480377546), (189.35717326521925, 135.89269746646795), (239.42103022562793, 159.09388971684052), (287.6117496807152, 187.81917536015894), (308.8974031502767, 205.49627421758566), (348.2332907620264, 246.374565325385), (366.1132396764581, 266.26130153999003), (389.272030651341, 301.6154992548435), (450.0638569604087, 307.13959264778936), (451.7667092379736, 57.45057128663686), (355.38527032779905, 55.24093392945852), (355.38527032779905, 66.28912071535022), (323.20136228182207, 66.28912071535022), (323.20136228182207, 55.24093392945852), (210.81311196253725, 55.24093392945852), (210.81311196253725, 60.765027322404364), (173.35036185610898, 60.765027322404364), (173.35036185610898, 55.24093392945852), (73.22264793529162, 51.926477893691), (71.51979565772669, 116.00596125186286), (107.27969348659005, 119.32041728763039)]
        holeb = [(749.9361430395913, 60.765027322404364), (498.254576415496, 57.45057128663686), (494.67858663260967, 294.9865871833085), (566.0280970625798, 301.6154992548435), (566.0280970625798, 292.77694982613014), (591.0600255427842, 292.77694982613014), (589.3571732652192, 303.8251366120218), (730.3533418475947, 315.9781420765027)]
          
        connected_polygon = connect([contour, holea, holeb])

        root = Tk()
        root.title(string='connect holes to contour / fill resulting polygon')
        canvas1 = Canvas(root, width=900, height=415, background='white')
        canvas1.pack()

        canvas1.create_polygon(contour, outline='blue', fill='')
        canvas1.create_text(contour[0], text='C(1)')
        canvas1.create_text(contour[20], text='C(i)')
        canvas1.create_text(contour[-1], text='C(n)')

        canvas1.create_polygon(holea, outline='red', fill='')
        canvas1.create_text(holea[0], text='H1(1)')
        canvas1.create_text(holea[9], text='H1(i)')
        canvas1.create_text(holea[-1], text='H1(n)')

        canvas1.create_polygon(holeb, outline='green', fill='')
        canvas1.create_text(holeb[0], text='H2(1)')
        canvas1.create_text(holeb[2], text='H2(i)')
        canvas1.create_text(holeb[-1], text='H2(n)')
        
        canvas1.create_text((10, 350), text='# More info in setup.py\n'
            'from pykbool import connect\n'
            'contour=[(... , ...) ... ]; hole1=[(... , ...) ... ]; hole2=...\n'
            'polygon=connect([contour, hole1, hole2, ...])', anchor=SW)
        
        canvas2 = Canvas(root, width=900, height=415, background='white')
        canvas2.pack()
        image=PhotoImage(file=os.path.join('data','demo.gif'))
        canvas2.create_image((0,0), image=image, anchor=NW)
        canvas2.image=image
        canvas2.create_polygon(connected_polygon, outline='black', fill='grey')
        canvas2.create_text(connected_polygon[0], text='P1')
        canvas2.create_text(connected_polygon[62], text='Pi')
        canvas2.create_text(connected_polygon[-1], text='Pn')

        root.mainloop()
开发者ID:decitre,项目名称:pykbool,代码行数:57,代码来源:setup.py

示例3: demo2

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
def demo2():
    try:
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas
        else:
            from Tkinter import Tk, Canvas
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        import json, gzip
        
        with gzip.open(os.path.join('data','poly.json.gz'), 'r') as f:
            contour, holes = json.loads(f.readline().decode())
        
        try:
            connected = connect([contour]+holes)

            root1 = Tk()
            root1.title(string='not connected - contour (%d points) + holes (%d points)'%(len(contour), sum(map(len, holes))))
            canvas1 = Canvas(root1, width=810, height=510, background='white')
            canvas1.pack()
            canvas1.create_polygon(contour, outline='blue', fill='')
            for hole in holes:
                canvas1.create_polygon(hole, outline='red', fill='')

            root2 = Tk()
            root2.title(string='connected - keyhole polygon (%d points)' %(len(connected)))
            canvas2 = Canvas(root2, width=810, height=510, background='white',)
            canvas2.pack()

            canvas2.create_polygon(connected, outline='black', fill='#98BAD3', dash=(4,))

            canvas2.create_text(connected[0], text='P1', fill='red')
            canvas2.create_text(connected[int(len(connected)*0.5)], text='Pi', fill='red')
            canvas2.create_text(connected[int(len(connected)*2/3)], text='Pj', fill='red')

            root1.mainloop()
        except:
            traceback.print_exc()
开发者ID:decitre,项目名称:pykbool,代码行数:43,代码来源:setup.py

示例4: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
class Plot:

    def __init__(self, root, grid, title='', boxsize=[], width=800, height=800):
        
        if boxsize:
            self.xmin, self.ymin, self.xmax, self.ymax = boxsize
        else:
            self.xmin, self.ymin, self.xmax, self.ymax = grid.boxsize()
        self.width = width
        self.height = height
        self.title = title
        self.grid = grid
    
        self.frame = Frame(root)
        self.frame.pack()
        self.canvas = Canvas(bg="white", width=width, height=height)
        self.canvas.pack()

    def draw(self, rho, the, xyPath=[]):
        
        border_x, border_y = 0.2, 0.2
        scale = min((1.-border_x)*self.width/(self.xmax-self.xmin), \
                    (1.-border_y)*self.height/(self.ymax-self.ymin))
        a = max(border_x * self.width/2., (self.width-scale*(self.xmax-self.xmin))/2.)
        b = max(border_y * self.height/2.,(self.height-scale*(self.ymax-self.ymin))/2.)
    
        box_pix = (a, self.height-scale*(self.ymax-self.ymin) - b,
                   scale*(self.xmax-self.xmin) + a, self.height - b)
        # draw the box
        self.addBox((self.xmin, self.ymin, self.xmax, self.ymax), box_pix)
    
        # color plot
        cells = cell.cell(self.grid)
        for index in range(len(cells.data)):
                ia, ib, ic = cells.data[index]
                xa, ya = scale*(self.grid.x(ia)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ia)-self.ymin) - b
                xb, yb = scale*(self.grid.x(ib)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ib)-self.ymin) - b
                xc, yc = scale*(self.grid.x(ic)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ic)-self.ymin) - b

                rhoAbc = (rho[ia] + rho[ib] + rho[ic])/3.0
                theAbc = (the[ia] + the[ib] + the[ic])/3.0
                color = colormap(rhoAbc, theAbc)
                self.canvas.create_polygon(xa, ya, xb, yb, xc, yc, fill=color)
        
        # add path if present
        index = 0
        for (x, y) in xyPath:
            xa, ya = scale*(x - self.xmin) + a, \
                self.height -scale*(y - self.ymin) - b
            self.canvas.create_oval(xa-5, ya-5,
                                    xa+5, ya+5)
            #self.canvas.create_text(xa+2, ya+1, text=str(index))
            index += 1
    
        # add title
        x, y = self.width/3., self.height/15.0
        self.canvas.create_text(x, y, text=str(self.title),
                                font =("Helvetica", 24),
                                fill='black')


    def addBox(self, xxx_todo_changeme, xxx_todo_changeme1):
        """
        Add Box. Min/Max coordinates are in pixels.
        """
        (self.xmin,self.ymin,self.xmax,self.ymax) = xxx_todo_changeme
        (self.xmin_pix, self.ymin_pix, self.xmax_pix, self.ymax_pix) = xxx_todo_changeme1
        self.canvas.create_line(self.xmin_pix, self.ymax_pix, self.xmax_pix, self.ymax_pix)
        self.canvas.create_text(self.xmin_pix   ,self.ymax_pix+ 8, text=('%4.1f' % self.xmin))
        self.canvas.create_text(self.xmin_pix-12,self.ymax_pix   , text=('%4.1f' % self.ymin))
        self.canvas.create_line(self.xmax_pix, self.ymax_pix, self.xmax_pix, self.ymin_pix)
        self.canvas.create_text(self.xmax_pix   ,self.ymax_pix+ 8, text=('%4.1f' % self.xmax))
        self.canvas.create_line(self.xmax_pix, self.ymin_pix, self.xmin_pix, self.ymin_pix)
        self.canvas.create_text(self.xmin_pix-12,self.ymin_pix   , text=('%4.1f' % self.ymax))
        self.canvas.create_line(self.xmin_pix, self.ymin_pix, self.xmin_pix, self.ymax_pix)
开发者ID:pletzer,项目名称:compos,代码行数:80,代码来源:plot.py

示例5: prgCanvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]

#.........这里部分代码省略.........
        lengthX = abs(mX-sX)
        lengthY = abs(mY-sY)
        if lengthX>0 and lengthY>0:
            cX = lX/lengthX
            cY = lY/lengthY
        else:
            cX,cY=1.0,1.0
        print("MSH",cX,cY)
        
        self.normalization = [abs(sX),abs(sY)]
        self.mashtab = int(min(cX,cY)*0.9)
    
    def transform(self,x,y,a,etalon):
        """
        точка отсчета - в центре эталона
        """
        new = list()
        for item in etalon:
            ca = cos(a)
            sa = sin(a)
            x2,y2 = item[0]-x, item[1]-y
            
            new.append([x2*ca + y2*sa+x, x2*sa - y2*ca+y])
        return new
        
    def genfield(self):
        x,y,d=0,1,2
        
        self.canvas.delete("all")

        for c in self.field:
            cx = (c[x]+self.normalization[x])*self.mashtab+self.reper[x]
            cy = (c[y]+self.normalization[y])*self.mashtab+self.reper[y]

            print("filter",self.filter)
            
            if self.flagDescription and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
                font = "Verdana 8"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif (not self.flagDescription) and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
            elif self.flagDescription and self.filter!=None and self.filter(c[d][2]):
                _color1,_color2 = ["red","red"]
                tag = "RED"
                font = "Verdana 10 bold"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif self.flagDescription:
                _color1,_color2 = "black","black"
                tag = "BLACK"
                # font = "Verdana 8"
                # self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
                pass
                
            # здесь может быть выбор фигуры
            # здесь может быть угол поворота
            print("c",c)
            if c[-2][0]=="25":
                angle = radians(c[-1])
                pattern = [[-3,-5.0],[3,-5.0],[0.0,3.0],[-3.0,-5.0]]
                et = [[cx+item[0],cy+item[1]] for item in pattern]
                new = self.transform(cx,cy,angle,et)
                self.canvas.create_polygon(new,activefill="white",fill=_color2,tag=("FIG",tag))
            else:
                self.canvas.create_rectangle(cx-1,cy-1,cx+1,cy+1,outline=_color1,fill=_color2,tag=("FIG",tag))
        self.canvas.tag_lower("RED")
        
    def move(self,x,y):
        #в группы
        self.reper[0]+=x
        self.reper[1]+=y
        self.canvas.move("FIG",x,y)
        self.canvas.move("DESC",x,y)

    def load(self):
        _p = prg(self.fileprogram)
        _p.download()
        _p.extract()
        #вариант кода для загрузки информации о установке
        self.field = [x[1:4]+[x[0]] for x in _p.progdigit if ("25" in x[3]) or ("107" in x[3])]
        print(_p.progdigit)
        #вариант кода для загрузки информации о дозировании:
        # self.field.group = [x[1:4] for x in _p.progdigit if "107" in x[3]]
        # print(self.field)

    def paint(self):
        self.load()
        try:
            self.setMashtab()
            self.genfield()
        except ZeroDivisionError:
            print("Zero division")
        except IndexError:
            print("Index error")
            #рисуем надпись
            self.canvas.delete("all")
            x,y = int(self.canvas["width"]),int(self.canvas["height"])
            self.canvas.create_text(x//2,y//2,text="FILE IS CORRUPTED", font="Verdana 12 bold",fill="red",tag="del")
开发者ID:sergnov,项目名称:PrgViewer,代码行数:104,代码来源:prgviewer.py

示例6: QuickHull

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
class QuickHull(Tk):
	def __init__(self,points):
		Tk.__init__(self)
		board = Frame(self)
		self.title("Diagram") 

		width = 800 #setting height and width
		height = 600

		windowx = self.winfo_screenwidth()
		windowy = self.winfo_screenheight()
		x = (windowx - width)/2		#getting center
		y = (windowy - height)/2

		self.geometry("%dx%d+%d+%d" % (width,height,x,y)) #creates window of size _width by _height, and positions it at the center of the screen

		board.pack(fill=BOTH, expand=1)
	
		self.canvas = Canvas(board,height=600,width=800,background="white")
		self.canvas.place(x=0,y=0)
		
		self.drawPoints(points) #Draw points and the first line from the highest an lowest points
		

					

		
		def point(event):  #Add points by clicking on the screen
			self.canvas.create_text(event.x, event.y,text = "+")
			points.append([event.x,event.y])

		def start():
			if(points != []):
				startB.destroy()
				quickHullStart(points)
				self.nextButton()
	
		self.canvas.bind("<Button-1>", point)
		
		startB = Button(self, text = "Start QuickHull", command = start)
		startB.pack()
	
		
	
		self.mainloop()
	
				
	def nextButton(self):					#Button that steps forward one step in the QuickHull
		def callBack():
			self.animate()

		continueB = Button(self, text="-->",command=callBack)
		continueB.place(x=350,y=550)


	def animate(self):						#animation loop
		if(triList == []):
			self.onExit()
			return
		self.canvas.create_polygon(triList.pop(0),fill="red",outline="black")
			





	def onExit(self):  #Window popup signaling that the Quick Hull is complete
		alert = Tk()
		finish = Window(alert)
		finish.config(title="Complete",w = 200, h=50)
		finish.positionWindow()

		done = Label(alert,text="QuickHull Complete")
		done.pack()

		ok = Button(alert,text="OK",command=alert.destroy)
		ok.pack()
		alert.mainloop()
		return
		


	def drawPoints(self,points):			#Draw points Imported from a file
		for p in points:
			self.canvas.create_text(p[0],p[1],text="+")
开发者ID:liangtianumich,项目名称:QuickHull,代码行数:87,代码来源:QuickHull.py

示例7: Game

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]

#.........这里部分代码省略.........
			else:
				n = self.defaultBoardArgs[0] + 1
		return n
	
	def keyboard(self, event):
		"""
		Keyboard Pressed
		"""
		#print(event.keysym)
	
	def mouse_b1(self, event):
		"""
		Mouse Left Button Pressed
		"""
		#print(event.x, ";", event.y)

	def getPlayerHexIndex(self):
		for index, t in enumerate(self.hexagons):
			if t.hasTag("Player"):
				return index
		return -1

	def getHexIndexByPosition(self, pos):
		for index, t in enumerate(self.hexagons):
			if t.position[0] == pos[0] and t.position[1] == pos[1]:
				return index
		return -1

	def getHexIndexByID(self, id):
		for index, t in enumerate(self.hexagons):
			if t.id == id:
				return index
		return -1
	
	def draw(self):
		"""
		Draws the whole game, should only be called once
		"""
		self.board_callback(self.draw_board, *self.defaultBoardArgs)

	def board_callback(self, callback, lowest_nb_of_rows = 2, nb_of_columns = 3, lowest_nb_of_rows_first = True, *args):
		"""
		This method calls a callback when a
		tile is supposed to be drawn
		"""
		for i in range(0, nb_of_columns):
			n = self.getBoardHeight(i)
			for j in range(0, n):
				callback(i, j, n, nb_of_columns, lowest_nb_of_rows, *args)
	
	def draw_board(self, i, j, n, nb_of_columns, lowest_nb_of_rows):
		"""
		Draws the game board composed of
		hexagons at the center of the window
		This is supposed to be called by board_callback
		"""
		pos = (i - int(nb_of_columns / 2), j - int(n / 2))
		if pos[0] == 0 and pos[1] == 0:
			self.hexagons.append(
				Tile(self,
					pos,
					-1,
					self.player)
			)
		else:
			self.hexagons.append(
				Tile(self,
					pos,
					-1)
			)
		self.draw_hexa(
			self.width / 2 +
				(i - .5 * nb_of_columns + .5) * self.hexa_size * .75,
			self.height / 2 +
				(j * 2 - lowest_nb_of_rows + 1 - n % lowest_nb_of_rows) *
				self.hexa_size * .375,
			self.hexa_size - 2,
			"red")
	
	def draw_hexa(self, x, y, size, color):
		"""
		Draws an hexagon centered at the given position (x, y)
		"""
		# Only half the size is needed
		# as size is the length of the longest
		# line contained in the hexagon
		# and we are working from the center of it
		size = size / 2
		index = len(self.hexagons) - 1
		self.hexagons[index].id = self.canvas.create_polygon(
				x - size, y,
				x - size / 2, y - size * .75,
				x + size / 2, y - size * .75,
				x + size, y,
				x + size / 2, y + size * .75,
				x - size / 2, y + size * .75,
				fill=color)
		self.hexagons[index].addTag('hexagon')
		self.hexagons[index].addTag()
		self.hexagons[index].drawEntity()
开发者ID:Tidaren,项目名称:ISN,代码行数:104,代码来源:game.py

示例8: World

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]

#.........这里部分代码省略.........
        text = str(self.beepers[(x, y)])
        a = self.t + x * self.t
        b = self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a-t, b-t, a+t, b+t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(a, b, text=text,
                                                           fill="white",
                                                           font=("Times",
                                                                 max(-self.t/2,
                                                                     -20),
                                                                 ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in list(self.robots.keys()):
            for robot in self.robots[(x, y)]:
                robot.lift()

    def remove_beeper(self, x, y):
        if self.beepers[(x, y)] is INFINITY:
            return
        self.beepers[(x, y)] -= 1
        flag = self.beepers[(x, y)] is 0
        text = str(self.beepers[(x, y)])
        if flag:
            self.canvas.delete(self.ovals[(x, y)])
            self.canvas.delete(self.numbers[(x, y)])
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in list(self.robots.keys()):
            for robot in self.robots[(x, y)]:
                robot.lift()

    def add_wall(self, x1, y1, x2, y2):
        if not x1 == x2 and not y1 == y2:
            return
        if x1 == x2:
            y1, y2 = min(y1, y2), max(y1, y2)
            if y1 == -1:
                y1 = y2
            for k in range(y1, y2+1):
                self.walls.setdefault((x1, k), []).append((x1+1, k))
                a = self.t + x1 * self.t+self.t / 2
                b = self.n - (self.t + k * self.t) + self.t / 2
                c = self.t + x1 * self.t + self.t / 2
                d = self.n - (self.t + k * self.t) - self.t / 2
                self.canvas.create_line(a, b+1, c, d-1, fill="black", width=3)
        else:
            x1, x2 = min(x1, x2), max(x1, x2)
            if x1 == -1:
                x1 = x2
            for k in range(x1, x2+1):
                self.walls.setdefault((k, y1), []).append((k, y1+1))
                a = self.t + k * self.t - self.t / 2
                b = self.n - (self.t + y1 * self.t) - self.t / 2
                c = self.t + k * self.t + self.t / 2
                d = self.n - (self.t + y1 * self.t) - self.t / 2
                self.canvas.create_line(a-1, b, c+1, d, fill="black", width=3)

    def draw(self, x, y, d, img):
        t = self.t / 2
        angle = 120
        x = self.t + x * self.t
        y = self.n - (self.t + y * self.t)
        x1 = x + 3 ** 0.5 * t / 2 * cos(radians(d))
        y1 = y - 3 ** 0.5 * t / 2 * sin(radians(d))
        x2 = x + t * cos(radians(d + angle))
        y2 = y - t * sin(radians(d + angle))
        x3 = x + t / 4 * cos(radians(d + 180))
        y3 = y - t / 4 * sin(radians(d + 180))
        x4 = x + t * cos(radians(d - angle))
        y4 = y - t * sin(radians(d - angle))
        if img is not None:
            self.canvas.delete(img)
        return self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4,
                                          fill="blue")

    def erase(self, img):
        self.canvas.delete(img)

    def record_move(self, count, x1, y1, x2, y2):
        for robot in self.robots[(x1, y1)]:
            if robot.count == count:
                self.robots[(x1, y1)].remove(robot)
                self.robots.setdefault((x2, y2), []).append(robot)
                break

    def lift(self, img):
        self.canvas.lift(img)

    def refresh(self):
        self.canvas.update()
        self.pause()

    def register(self, x, y, robot):
        self.robots.setdefault((x, y), []).append(robot)

    def remove(self, x, y, robot):
        self.robots[(x, y)].remove(robot)
开发者ID:jelkner,项目名称:pykarel,代码行数:104,代码来源:pykarel.py

示例9: Application

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]

#.........这里部分代码省略.........

    def send_shape_details_and_restart(self):
        """
        This function called when the user completed a shape
        it send to communicator a message the says "New shape was added"
        """
        self.__network.shape_msg([self.__drawing_shape, self.__points, self.__user_color.get()])
        self.__current_shape = None
        self.__drawing_shape = None
        self.__points = []
        self.canvas.config(cursor="")



    def draw_shape(self, points, s_type, user_name, color):
        """
        This function draw a new shape on the screen
        :param points: "x,y,z,w,a,b" string
        that each odd nu is x and each even is y
        :param s_type: shape type, string
        :param user_name: user_name string
        :param color: color, string
        """
        if s_type == LINE:
            self.canvas.create_line(points,
                                    fill=color, width=LINE_WIDTH)
        elif s_type == SQUARE:
            self.canvas.create_rectangle(points,
                                         fill=color)
        elif s_type == ELIPSE:
            self.canvas.create_oval(points,
                                    fill=color)
        elif s_type == TRIANGLE:
            self.canvas.create_polygon(points,
                                       fill=color)
        self.canvas.create_text(points[:FIRST_XY],
                                text=user_name)
        self.debug_event("draws: " + s_type)

    def points_to_tuple(self, str_points):
        """
        this function gets alot of numbers in string and returns
        :param str_points: "x,y,z,w,a,b" string
        that each odd nu is x and each even is y
        :return: list of coordinates as tuple in format (x,y,x,y,x,y)
        """
        nums = str_points.split(',')
        return tuple(nums)

    def open_help_dialog(self):
        """
        This function creates new "help" dialog
        :return:
        """
        try:
            self.help_frame.destroy()
        except:
            pass
        infromative_txt = self.get_informative_text()
        self.help_frame = Tk()
        self.help_frame.title(HELP_TITLE)
        infromative_text = Label(self.help_frame, text=infromative_txt)
        infromative_text.pack()
        self.help_frame.mainloop()

    def get_informative_text(self):
开发者ID:Omertorren,项目名称:ex12,代码行数:70,代码来源:client.py

示例10: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_polygon [as 别名]
class IsometricViewer:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.wireframe = True
        self.drawables = []
        self.items = {}
        self.text = ""
        self.theta = 0
        self.phi = 0
        self.scale = 0
        self.x_offset = 0
        self.y_offset = 0
        self.canvas = Canvas(Tk(), width=self.width, height=self.height)
        self.reset_viewport()
        self.init_gui()
    @property
    def camera_coords(self):
        return Point3(math.cos(self.theta) * math.cos(self.phi), -math.sin(self.theta) * math.cos(self.phi), math.sin(self.phi))
    def reset_viewport(self):
        self.theta = math.pi / 8
        self.phi = math.pi / 16
        self.scale = 1
        self.x_offset = self.width / 2
        self.y_offset = self.height / 2
    def init_gui(self):
        self.canvas.pack()
        self.canvas.focus_set()
        self.canvas.bind("<Up>", self._callback_commandline_up)
        self.canvas.bind("<Down>", self._callback_commandline_down)
        self.canvas.bind("<Left>", self._callback_commandline_left)
        self.canvas.bind("<Right>", self._callback_commandline_right)
        self.canvas.bind("=", self._callback_commandline_equal)
        self.canvas.bind("-", self._callback_commandline_minus)
        self.canvas.bind("<Shift-Up>", self._callback_commandline_shift_up)
        self.canvas.bind("<Shift-Down>", self._callback_commandline_shift_down)
        self.canvas.bind("<Shift-Left>", self._callback_commandline_shift_left)
        self.canvas.bind("<Shift-Right>", self._callback_commandline_shift_right)
        self.canvas.bind("<Shift-Return>", self._callback_commandline_shift_return)
        self.canvas.bind("<Button-1>", self._callback_button_1)
        self.canvas.bind("<B1-Motion>", self._callback_button_1_motion)
    def add_drawable(self, drawable):
        assert isinstance(drawable, Drawable)
        self.drawables.append(drawable)
    def project(self, point):
        projected = point.rotate(self.theta, self.phi)
        return Point2(projected.y * self.scale + self.x_offset, -projected.z * self.scale + self.y_offset)
    def unproject(self, point):
        return point.rotate(0, -self.phi).rotate(-self.theta, 0)
    def move_camera(self, theta, phi):
        self.theta += theta
        if self.theta > 2 * math.pi:
            self.theta -= 2 * math.pi
        elif self.theta < 0:
            self.theta += 2 * math.pi
        if -math.pi / 2 <= self.phi + phi <= math.pi / 2:
            self.phi += phi
    def clear(self):
        for item in self.items:
            self.canvas.delete(item)
    def draw_line(self, owner, p1, p2, **kargs):
        assert isinstance(p1, Point3)
        assert isinstance(p2, Point3)
        p1 = self.project(p1)
        p2 = self.project(p2)
        item = self.canvas.create_line(p1.x, p1.y, p2.x, p2.y, **kargs)
        self.items[item] = owner
        return item
    def draw_ellipse(self, owner, corners, **kargs):
        assert all(isinstance(p, Point3) for p in corners)
        item = self.draw_polygon(owner, corners, outline="#000000", smooth=1, **kargs)
        self.items[item] = owner
        return item
    def draw_polygon(self, owner, pts, **kargs):
        assert all(isinstance(p, Point3) for p in pts)
        args = []
        for p in pts:
            p = self.project(p)
            args.extend((p.x, p.y))
        item = self.canvas.create_polygon(*args, **kargs)
        self.items[item] = owner
        return item
    def draw_wireframe(self):
        for drawable in self.drawables:
            drawable.draw_wireframe(self)
    def draw(self):
        for drawable in self.drawables:
            drawable.draw(self)
    def update(self):
        self.clear()
        header = [
            "(theta, phi): ({:.3f}, {:.3f})".format(self.theta, self.phi),
            "(x, y, z): {}".format(self.camera_coords),
        ]
        text = "\n".join(header) + "\n\n" + self.text
        item = self.canvas.create_text((10, 10), anchor="nw", text=text)
        self.items[item] = None
        if self.wireframe:
            self.draw_wireframe()
        else:
#.........这里部分代码省略.........
开发者ID:justinnhli,项目名称:routesmith,代码行数:103,代码来源:routesmith.py


注:本文中的tkinter.Canvas.create_polygon方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。