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


Python Canvas.find_withtag方法代码示例

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


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

示例1: TKinterDisplay

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

#.........这里部分代码省略.........
    def renderTextInId(self, tagTocentreOn, tagsToAddTo, content, funcContent):
        id1tuple = self.__getCoords(tagTocentreOn)
        x1 = id1tuple[0] + ((id1tuple[2] - id1tuple[0]) / 2)
        y1 = id1tuple[1] + ((id1tuple[3] - id1tuple[1]) / 2)       
        txt = self.__renderText(x1, y1, (id1tuple[2] - id1tuple[0]), content, tagsToAddTo)
        
        def handler(event, self=self, content=funcContent):
            return self.__eventOnClick(event, content)
        
        self.localCanvas.tag_bind(txt, "<ButtonRelease-1>", handler)
        return txt
    
    @abstractmethod
    def move(self, tag, xamount, yamount):
        self.localCanvas.move(tag, xamount, yamount)

    @abstractmethod    
    def runDisplay(self):
        self.localCanvas.mainloop()
    
    
    def __hideId(self, objectId):
        self.localCanvas.itemconfigure(objectId, state="hidden")
        pass
        
    def __showId(self, objectId):
        self.localCanvas.itemconfigure(objectId, state="normal")
        pass
    
    def __sampleDraw(self):
        self.localCanvas.create_oval(0, 0, 0, 0, width=0)
    
    def __renderText(self, x, y, width, content, tag):
        val = self.localCanvas.create_text(x, y, width=width, text=content, tags=tag, justify="center", font="Helvetica 8 bold", anchor="center")
        self.localCanvas.tag_raise(val)
        return val
    
    def __drawLine(self, x1, y1, x2, y2, tags=None, colour="black"):
        line = self.localCanvas.create_line(x1, y1, x2, y2, tags=tags, width=self.lineThickness, arrow="first", arrowshape=(16,20,6),fill=colour, smooth=True)
        self.localCanvas.tag_lower(line)
        return  # line
    
    def __remove(self, num):
        self.localCanvas.delete(num)
    
    def __getCoords(self, ident):
        return self.localCanvas.coords(ident)
    
    def __eventOnFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        assert self.localCanvas
        coord_tuple = self.localCanvas.bbox("all")
        if not coord_tuple:
            logging.error("Frame reconfigure error on coordinate acquire.")
        else:
            reconWidth = coord_tuple[2] - coord_tuple[0]
            reconHeight = coord_tuple[3] - coord_tuple[1]
            self.localCanvas.configure(width=reconWidth)
            self.localCanvas.configure(height=reconHeight)
            self.localCanvas.configure(scrollregion=self.localCanvas.bbox("all"))
            self.localCanvas.update_idletasks()
    
    def __eventOnClick(self, event, content):
        self.__createWindowOnId(self.localCanvas.find_withtag(CURRENT), content)
        
    def __createWindowOnId(self, itemId, content):
        if self.currentlyRenderedWindow != None:
            self.currentlyRenderedWindow()
        # self.__remove(self.currentlyRenderedWindow)
        idtuple = self.localCanvas.coords(itemId)
        if idtuple:
            x = idtuple[0]
            y = idtuple[1]
            frm = Frame(self.localCanvas)
            frm.grid(row=0, column=0)
            canv = Canvas(frm)            
            
            vscroll = Scrollbar(frm, orient="vertical", command=canv.yview)
            vscroll.grid(row=0, column=1, sticky=N + S)
            
            canv.grid(row=0, column=0)
            
            canv["yscrollcommand"] = vscroll.set
            aframe = Frame(canv)
            aframe.grid(row=0, column=0)
            Label(aframe, text=content, anchor="center", background="#CCFFCC", borderwidth=6, relief="ridge", justify="left").grid(row=1, column=0)
            canvWindow = canv.create_window(x, y, window=aframe)
            canv.coords(canvWindow, x, y)
            self.localCanvas.update_idletasks()
            canv["scrollregion"] = canv.bbox("all")
            
            def destroyAll():
                self.__remove(canvWindow)
                canv.destroy()
                aframe.destroy()
                vscroll.destroy()
                frm.destroy()
                
            self.currentlyRenderedWindow = destroyAll 
            Button(frm, text="Close", command=lambda :  destroyAll()).grid(row=2, column=0)
开发者ID:Capgemini,项目名称:PyPomVisualiser,代码行数:104,代码来源:TKinterDisplay.py

示例2: Game

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import find_withtag [as 别名]
class Game(object):
	"""
	"""
	def __init__(self, wnd, w, h):
		"""
		"""
		Database.init()
		self.hexa_size = 80
		self.width = w
		self.height = h
		self.canvas = Canvas(
			wnd, width=self.width, height=self.height,
			bg='#0080FF', highlightthickness=0, bd=0)
		self.canvas.pack()
		wnd.resizable(False, False)
		self.player = Player(1)
		self.inventory = Inventory()
		self.hexagons = []
		self.defaultBoardArgs = (2, 3, True)

		self.canvas.tag_bind('hexagon', "<Button-1>", self.hexAction)

		# TODO : Remove these tests
		self.player.debug()
		Database.debug_items()
		self.inventory.addItem(0)
		self.inventory.addItem(1)
		self.inventory.addItem(0)
		self.inventory.addItem(2)
		self.inventory.addItem(0)
		self.inventory.debug()
		Database.debug_enemies()

	def hexAction(self, event):
		tmp = self.canvas.find_withtag(CURRENT)
		if tmp:
			id = tmp[0]
			index = self.getHexIndexByID(id)
			if self.hexagons[index].hasTag('Player'):
				print("Action: Open Inventory")
			elif self.hexagons[index].hasTag('Enemy'):
				print("Action: Attack")
			else:
				print("Action: Move")
				movePos = self.hexagons[index].position
				if movePos[0] == 0 and movePos[1] == 0:
					return
				def move(t, nIndex):
					self.hexagons[nIndex].setEntity(t.entity)
					t.unsetEntity()

				move(self.hexagons[self.getPlayerHexIndex()], index)
				doneIDs = []
				def moveUtil(t):
					nPos = [t.position[0] - movePos[0], t.position[1] - movePos[1]]
					if nPos[0] % 2 and not t.position[0] % 2:
						nPos[1] -= 1
					nPos = tuple(nPos)
					nIndex = self.getHexIndexByPosition(nPos)
					if nIndex == -1:
						if not((nPos[0] < t.position[0] and nPos[1] < t.position[0]) or (nPos[0] > t.position[0] and nPos[1] == t.position[1])):
							t.unsetEntity()
						doneIDs.append(t.id)
						return
					if not nIndex in doneIDs:
						moveUtil(self.hexagons[nIndex]) # Bad recursion... but works with small boards
					move(t, nIndex)
					doneIDs.append(t.id)
				for t in self.hexagons:
					if t.id in doneIDs:
						continue
					moveUtil(t)

	def getBoardWidth(self, row=-1):
		return self.defaultBoardArgs[1]

	def getBoardHeight(self, column):
		# This code is a bit tricky
		# Since the board is composed of hexagons
		# The height isn't the same on every row
		# (at least that's how we handled everything)
		# We use the self.defaultBoardArgs
		# Basically, it'll handle the board's form
		# If self.defaultBoardArgs[2] is True, then the first
		# column will have the lowest number
		# of rows, eg. if self.defaultBoardArgs[0] is set to 2
		# then the first column will have 2 rows
		# The other columns have 1 more row
		# The best way to understand is to try it x)
		n = 0
		if column % 2 :
			if self.defaultBoardArgs[2]:
				n = self.defaultBoardArgs[0] + 1
			else:
				n = self.defaultBoardArgs[0]
		else:
			if self.defaultBoardArgs[2]:
				n = self.defaultBoardArgs[0]
			else:
				n = self.defaultBoardArgs[0] + 1
#.........这里部分代码省略.........
开发者ID:Tidaren,项目名称:ISN,代码行数:103,代码来源:game.py

示例3: Board

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

#.........这里部分代码省略.........
                    self.redPointsVariableLabel.setVar(self.redPointsVariableLabel.getVar().get()+1)
                else:
                    self.bluePointsVariableLabel.setVar(self.bluePointsVariableLabel.getVar().get()+1)

            destCoordX1,destCoordY1,destCoordX2,destCoordY2=self.getGuiCoord(dest[1],dest[0])
            currentCellId=self.draw_circle(destCoordX2,destCoordY2,destCoordX1,destCoordY1, playerColor, tag,playerColor)#placement du pion déplacé

            if (cap): self.selectPawn(currentCellId,tag)#Après capture, le pion est toujours sélectionné
            self.hasPlayed=True

            if(not(self.hasCaptured)): self.changePlayer(currentCellId,i,j)#Aucune capture, changement de joueur

        else:
            departA=self.coordToLetter(ancientSelectedCellTags[0][1])
            departB=str(int(ancientSelectedCellTags[0][2])+1)
            destA=self.coordToLetter(i)
            destB=str(j+1)
            message="le coup "+departA+departB+"-"+destA+destB+" n'est pas permis"+"\n"+dr.strerr(errCode)
            MessageBox("ERROR "+str(errCode),message)




    def selectPawn(self,currentCellId,tag):
        """

        :param currentCellId: id de la case a selectionner
        :param tag: tags du pion
        """
        self.guiBoard.itemconfig(currentCellId,fill="green",tags=(tag,"selected"))

    def deselectPawn(self,ancientSelectedCellId,playerColor,ancientSelectedCellTags):
        """

        :param ancientSelectedCellId: id de la case précédemment sélectionnée
        :param playerColor: couleur du joueur (red ou blue)
        :param ancientSelectedCellTags: tags de la case précédemment sélectionnée
        """
        self.guiBoard.itemconfig(ancientSelectedCellId,fill=playerColor,tags=ancientSelectedCellTags[0])

    def getGuiCoord(self,i,j):

        """

        :param i: coordonnée x
        :param j: coordonnée y
        :return: les coordonnées des coins supérieur gauche et inférieur droit de la case
        """
        coordX1 = (i * self.cellSize)
        coordY1 = (j * self.cellSize)
        coordX2 = coordX1 + self.cellSize
        coordY2 = coordY1 + self.cellSize
        return(coordX1,coordY1,coordX2,coordY2)

    def bindEvent(self,event):
        i = int(event.x / self.cellSize)
        j = int(event.y / self.cellSize)
        if(dr.outside(self.logicBoard,j,i)): return
        playerColor="red" if self.player==1 else "blue"

        if(dr.caseNoire(j,i)):#Si l'on a cliqué sur une case noire

            coordX1,coordY1,coordX2,coordY2=self.getGuiCoord(i,j)
            tag="c"+str(i)+str(j)
            if (dr.isFree(self.logicBoard,j,i)):#Si l'on a cliqué sur une case vide
                currentCellId=self.guiBoard.find_withtag("r"+str(i)+str(j))[0]#recherche de l'ID de la case vide
            else:#Si l'on a cliqué sur un pion
                currentCellId=self.guiBoard.find_withtag(tag)[0]#recherche de l'ID du pion

            ancientSelectedCellId=self.guiBoard.find_withtag("selected")#recherche de l'ancienne case sélectionée

            if (ancientSelectedCellId):#Si une case à déjà été sélectionnée

                ancientSelectedCellId=ancientSelectedCellId[0]#On récupère l'id du tuple
                ancientSelectedCellTags=self.guiBoard.gettags(ancientSelectedCellId)#On récupère les tags de la case qui était selectionée
                ancientSelectedCellCoordI=int(ancientSelectedCellTags[0][1])
                ancientSelectedCellCoordJ=int(ancientSelectedCellTags[0][2])

                if (not(dr.isFree(self.logicBoard,j,i))):#Si on sélectionne une case remplie

                    if (self.hasCaptured==True):#Si l'on a déjà capturé

                        if (ancientSelectedCellCoordJ==j and ancientSelectedCellCoordI==i and dr.playerColor(self.logicBoard[j][i])==self.player):
                            #J'ai cliqué sur moi même : Tour fini
                            self.changePlayer(ancientSelectedCellId,i,j)
                            self.deselectPawn(ancientSelectedCellId,playerColor,ancientSelectedCellTags)
                            return

                    elif (dr.playerColor(self.logicBoard[j][i])==self.player):#Si on selectionne un de nos pions
                        self.deselectPawn(ancientSelectedCellId,playerColor,ancientSelectedCellTags)
                        self.selectPawn(currentCellId,tag)
                        return

                self.moveGuiPiece(i,j,ancientSelectedCellTags,ancientSelectedCellCoordJ,ancientSelectedCellCoordI,ancientSelectedCellId,playerColor)

            else:#Aucune case n'était sélectionnée

                if(not(dr.isFree(self.logicBoard,j,i))):
                    if (dr.playerColor(self.logicBoard[j][i])==self.player):
                        self.selectPawn(currentCellId,tag)
开发者ID:malikfassi,项目名称:draughts,代码行数:104,代码来源:draughtsGUI.py


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