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


Python Canvas.gettags方法代码示例

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


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

示例1: GUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import gettags [as 别名]
class GUI(Frame):
    def __init__(self, game, size, margin, colors=('black', 'white'), master=None):
        color = '#333333'
        Frame.__init__(self, master, bg=color)
        self.game = game
        self.cell_size = (size - 2*margin) / self.game.size
        self.coordinates = lambda position: self.cell_size * (np.array(position) + 1/2) + margin
        self.player_move = lambda event: self.move(pause=1000, event=event)
        self.grid()
        self.master.title("Pythello")
        self.colors = colors[::-1]  # Flip color order so that the first color input corresponds to player 1

        max_turns = self.game.size**2 - 4
        figure = Figure(figsize=(size/100, size/100), dpi=100, facecolor=color)
        axes = figure.add_subplot(111, axisbg=color)
        self.line = axes.plot(0, 0, 'w-', [0, max_turns], [0, 0], 'w--')[0]
        axes.grid(True, color='w')
        axes.set_xlim(0, max_turns)
        axes.set_ylim(-max_turns, max_turns)
        [tick.set_color('w') for axis in [axes.xaxis, axes.yaxis] for tick in axis.get_ticklines()]
        [label.set_color('w') for axis in [axes.xaxis, axes.yaxis] for label in axis.get_ticklabels()]
        [axes.spines[side].set_color('w') for side in ['top', 'bottom', 'left', 'right']]

        self.canvas = Canvas(self, width=size, height=size, background=color, highlightthickness=0)
        self.canvas.create_rectangle(margin, margin, size - margin, size - margin, outline='white')
        self.canvas.grid(row=0, column=1, rowspan=50)
        self.figure = FigureCanvasTkAgg(figure, master=self)
        self.figure.get_tk_widget().grid(row=0, column=2, rowspan=50)
        self.refresh()

        if all([isinstance(player, AI) for player in self.game.players]):
            self.play_button = Button(self, text='Play', highlightbackground=color, command=self.play)
            self.move_button = Button(self, text='Move', highlightbackground=color, command=self.move)
            self.reset_button = Button(self, text='Reset', highlightbackground=color, command=self.reset)
            self.play_button.grid(row=0, column=0)
            self.move_button.grid(row=1, column=0)
            self.reset_button.grid(row=2, column=0)
            self.running = False
        else:
            Button(self, text='Reset', highlightbackground=color, command=self.reset).grid(row=0, column=0)
            self.running = True

        for i in range(self.game.size):
            line_shift = self.cell_size * (i+1) + margin
            self.canvas.create_text(margin-10, line_shift - self.cell_size/2, text=str(i+1), fill='white')
            self.canvas.create_text(line_shift - self.cell_size/2, margin-10, text=chr(97+i), fill='white')
            self.canvas.create_line(margin, line_shift, size - margin, line_shift, fill='white')
            self.canvas.create_line(line_shift, margin, line_shift, size - margin, fill='white')

    def configure_buttons(self):
        (state, text, command) = ('disabled', 'Pause', self.pause) if self.running else ('normal', 'Reset', self.reset)
        self.play_button.config(state=state)
        self.move_button.config(state=state)
        self.reset_button.config(text=text, command=command)

    def draw_piece(self, position, radius, color):
        (y, x) = self.coordinates(position)
        return self.canvas.create_oval(x-radius, y-radius, x+radius, y+radius, fill=color, tags='circle')

    def move(self, pause=10, event=None):
        if event is None:
            move = self.game.player.move(self.game)
        else:
            move = eval(self.canvas.gettags(event.widget.find_withtag("current"))[-2])

        self.game.move(move)
        is_over = self.game.is_over()
        self.refresh()

        if not is_over and isinstance(self.game.player, AI) and self.running:
            self.after(pause, self.move)
        elif is_over:
            self.reset_button.config(text='Reset', command=self.reset)

    def pause(self):
        self.running = False
        self.configure_buttons()

    def play(self):
        self.running = True
        self.configure_buttons()
        self.move()

    def refresh(self):
        self.line.set_data(range(len(self.game.score)), self.game.score)
        self.figure.draw()
        [self.canvas.delete(tag) for tag in ['circle', 'text']]

        for position in zip(*np.nonzero(self.game.board)):
            color = self.colors[int((self.game.board[position] + 1) / 2)]
            self.draw_piece(position, (self.cell_size-2) / 2, color)

        if not isinstance(self.game.player, AI):
            for position in self.game.valid:
                (y, x) = self.coordinates(position)
                turned = len(self.game.valid[position]) - 1
                valid = self.draw_piece(position, self.cell_size / 4, 'green')
                self.canvas.addtag(str(position), 'withtag', valid)
                text = self.canvas.create_text(x+1, y+1, text=str(turned), tags=('text', str(position)))
                [self.canvas.tag_bind(tag, "<Button-1>", self.player_move) for tag in [valid, text]]
#.........这里部分代码省略.........
开发者ID:klane,项目名称:pythello,代码行数:103,代码来源:gui.py

示例2: Board

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import gettags [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.gettags方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。