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


Python Canvas.bind方法代码示例

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


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

示例1: Main

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.info = {}
        self.window = None
        self.size = (640, 480)
        self.fields = []
        self.init_ui()

    def init_ui(self):
        self.parent.title("Node Writer")
        self.style = Style()
        self.style.theme_use("alt")
        self.pack(fill="both", expand=True)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        menubar.add_command(label="New", command=self.onNew)
        menubar.add_command(label="Show Info", command=self.get_info)
        menubar.add_command(label="Exit", command=self.quit)

        self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1])
        self.canvas.pack(fill="both", expand=1)
        self.canvas.bind("<Motion>", self.move_boxes)

    def move_boxes(self, event):
        print(event.x, event.y)
        """
        x, y = (event.x-1, event.y-1)
        x1, y1, x2, y2 = self.canvas.bbox("test")
        if x > x1 and y > y1 and x < x2 and y < y2:
            print("Hit")
        else:
            print("Missed")
        """

    def onNew(self):
        new = Node(self, "Node_entry")
        label = new.insert_entry_field("Labels")
        label2 = new.insert_entry_field("Labels2")
        text = new.insert_text_field("Text")
        new.ok_cancel_buttons()

    def get_info(self):
        x, y = (self.size[0]/2, self.size[1]/2)
        for i in self.info:
            label_frame= LabelFrame(self, text="name")
            label_frame.pack(fill="y")
            for entry in self.info[i]["Entry"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
            for text in self.info[i]["Text"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Text"][text], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
        window = self.canvas.create_window(x, y, window=label_frame, tag="test")
开发者ID:Exodus111,项目名称:Projects,代码行数:62,代码来源:main.py

示例2: simulation_canvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
def simulation_canvas(parent, **config):
    """Initializes the canvas and sets it up to receive user input."""
    global the_canvas
    the_canvas = Canvas(parent, **config)
    the_canvas.focus_set()  # this makes tkinter canvas accept keyboard commands
    the_canvas.bind("<Key>", lambda event: model.move_ship(event))
    return the_canvas
开发者ID:kishanrajasekhar,项目名称:UFO-Ambush,代码行数:9,代码来源:controller.py

示例3: ListDialog

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
开发者ID:gokai,项目名称:tim,代码行数:60,代码来源:dialog.py

示例4: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        self._canvas = canvas
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
            if interior.winfo_reqheight() != canvas.winfo_height():
                # update the canvas's height to fit the inner frame
                canvas.config(height=interior.winfo_reqheight())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            """
            This function is called when the canvas is configured, that is on resize and so on,
            """
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
            if interior.winfo_reqheight() != canvas.winfo_height():
                # update the inner frame's height to fill the canvas
                canvas.itemconfigure(interior_id, height=canvas.winfo_height())

        canvas.bind('<Configure>', _configure_canvas)

        return
开发者ID:OptimalBPM,项目名称:qal,代码行数:52,代码来源:widgets_misc.py

示例5: SolutionViewer

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class SolutionViewer(object):
    '''Feed it progressively enhanced solutions in a loop:
    
    solution = initial
    while sv.show_and_wait(solution):
        new_solution = elaborate(solution)
        if new_solution is None:
            return solution
    '''
    
    def __init__(self):
        self.action = None
        self.root = root = Tk()
        root.title('Fold me baby one more time')
        root.protocol("WM_DELETE_WINDOW", self.close)
        
        # exists the mainloop()
        root.bind("<space>", lambda evt: root.quit())

        root.pack_propagate(True)

        self.canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
        self.canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        self.canvas.bind("<Configure>", lambda evt: self.populate_canvas())
        self.current_solution = None


    def populate_canvas(self):
        if self.current_solution is None:
            return
        draw_solution(self.canvas, self.current_solution)


    def show_and_wait(self, solution):
        '''Return False if user closed the window'''
        self.current_solution = solution
        self.populate_canvas() 
        self.root.mainloop()
        return self.root is not None


    def close(self):
        if self.root:
            self.root.destroy()
            self.root = None
开发者ID:Vlad-Shcherbina,项目名称:icfpc2016-tbd,代码行数:47,代码来源:tkrender.py

示例6: __init__

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

    def __init__(self, master):
        frame = Frame(master, borderwidth=5)
        frame.grid(column=0, row=0, pady=5)

        self.state = []
        self.states = 256
        self.laststate = 2  # 0=Black, 1=White, 2=Transp.

        self.size = 16
        self.gridsz = 20

        for x in range(1024):
            self.state.append(2)

        self.screen = Canvas(frame, height=320, width=320, bg=color[2])
        self.screen.bind("<Button-1>", self.scrnclick1)
        self.screen.bind("<Button-3>", self.scrnclick2)
        self.screen.bind("<B1-Motion>", self.scrndrag)

        for x in range(16):
            self.screen.create_line((x * 20, 0, x * 20, 320), fill=color[3])
            self.screen.create_line((0, x * 20, 320, x * 20), fill=color[3])

        self.screen.grid(row=0, column=0, columnspan=5)

        frame2 = Frame(master, borderwidth=5)
        frame2.grid(column=0, row=1, pady=5)

        self.clear = Button(frame2, text="Clear", command=self.clearit)
        self.clear.grid(row=0, column=0, pady=20)

        self.doit = Button(frame2, text="Print", command=self.doit)
        self.doit.grid(row=0, column=1, pady=20)

        #self.doitlab = Label(frame2, text="(Output to stdout)");
        #self.doitlab.grid(row=1, column=1);

        self.parse = Button(frame2, text="Parse", command=self.parsetext)
        self.parse.grid(row=0, column=2, pady=20)

        self.large = 0
        self.dummy = IntVar()
        self.largeb = Checkbutton(frame2, text="Large", var=self.dummy, command=self.changesize)
        self.largeb.grid(row=0, column=3, pady=20)

        self.prev = Canvas(frame2, height=17, width=17, bg=color[2], relief=RIDGE)
        self.prev.grid(row=0, column=4, pady=20, padx=20)

        # DataParsers
        self.bmlabel = Label(frame2, text="Bitmap Data (paste hex from code)")
        self.bmlabel.grid(row=2, column=0, columnspan=5, sticky="W")

        self.bmentry = Text(frame2, width=80, height=9, font="Times 8")
        self.bmentry.bind("<Leave>", self.bmtextpaste)
        self.bmentry.grid(row=3, column=0, columnspan=5, pady=5)

        self.msklabel = Label(frame2, text="Mask Data (paste hex from code)")
        self.msklabel.grid(row=4, column=0, columnspan=5, sticky="W")

        self.mskentry = Text(frame2, width=80, height=9, font="Times 8")
        self.mskentry.bind("<Leave>", self.msktextpaste)
        self.mskentry.grid(row=5, column=0, columnspan=5, pady=5)

    def changesize(self):
        self.large = ~self.large
        if self.large:
            self.size = 32
            self.gridsz = 10
            self.states = 1024
            oldstate = self.state
            self.state = []
            for n in range(1024):
                col = (n // 2) % 16
                row = int(n // 64)
                self.state.append(oldstate[16 * row + col])
            oldstate = []
        else:
            self.size = 16
            self.gridsz = 20
            self.states = 256
            oldstate = self.state
            self.state = []
            for n in range(1024):
                if not((n % 2) or ((n // 32) % 2)):
                    self.state.append(oldstate[n])
            for n in range(256, 1024):
                self.state.append(2)
            oldstate = []

        # Insert scaling here

        self.updatescrn()
        self.prev.config(width=self.size + 1, height=self.size + 1)
        for n in range(self.states):
            self.updateprev(n)
        #self.prev.grid(row=0, column=4, padx=self.gridsz, pady=self.gridsz)

    def scrnclick1(self, event):
#.........这里部分代码省略.........
开发者ID:fjuhec,项目名称:blender-dev-tools,代码行数:103,代码来源:make_cursor_gui.py

示例7: Graph

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class Graph(object):
    def __init__(self, title="GoBang15", gem_sz=600, board_sz=15):
        self.title = title
        self.sz = gem_sz
        self.board_cols = board_sz
        self.board_rows = board_sz

        self.init_root()
        self.init_canvas()
        self.init_bind()

    def init_root(self):
        self.root = tk.Tk()
        self.root.title(self.title)
        self.root.geometry(str(self.sz) + "x" + str(self.sz))

    def init_canvas(self):
        self.canvas = Canvas(self.root,width=600,height=600,borderwidth=3,background='white')
        self.canvas.pack()
        # CheckerBoard
        self.startX = (600 - 15 * 30) / 2
        self.startY = (600 - 15 * 30) / 2
        for num in range(0, self.board_cols + 1):
            self.canvas.create_line(self.startX + num * 30, 0 + self.startY, self.startX + num * 30, self.startY + 450, width=2)
        for num in range(0, self.board_rows + 1):
            self.canvas.create_line(self.startX + 0, self.startY + num * 30, self.startX + 450, self.startY + num * 30, width=2)

    def init_bind(self):
        global msg
        global player_id
        global player_move
        self.root.bind("<<showmsg>>", lambda event: self.show_msg(event, msg))
        self.canvas.bind("<<update>>", lambda event: self.update_graph(event,player_id, player_move))

    def show(self):
        self.root.mainloop()

    def cross(self, X, Y):
        """
        :param X:  小方格左上角的坐标
        :param Y:
        """
        cross_sz = 10
        self.canvas.create_line(X + cross_sz, Y + cross_sz, X - cross_sz, Y - cross_sz, width=4, fill="red")
        self.canvas.create_line(X - cross_sz, Y + cross_sz, X + cross_sz, Y - cross_sz, width=4, fill="red")
    def circle(self, X, Y):
        d = 20
        self.canvas.create_oval(X - d / 2, Y - d / 2, X + d / 2, Y + d / 2, width=4, outline='green')

    def update_graph(self, event, player_id, move):
        # AI确定落子位置后,在tkinter上显示出来
        row, col = move
        boardX = col * 30 + self.startX
        boardY = row * 30 + self.startY
        if player_id == 1:
            self.cross(boardX + 15, boardY + 15) #AI用cross
        else:
            self.circle(boardX + 15, boardY + 15)


    def show_msg(self, event, msg):
        tk.messagebox.showinfo(title="Game Over", message=msg)
开发者ID:chenxingqiang,项目名称:ML_CIA,代码行数:64,代码来源:gobang.py

示例8: BoardArea

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class BoardArea(Observer):
    '''
    Represent the area in which the player will play.
    
    @ivar _regions: Dictionary <game cell, screen rectangle>
    @ivar _selection: the current cell selected to move.
        If there's no selection, the value is None.
    '''
    
    def __init__(self, game, parent):
        '''Initialize the canvas, the observers and the mouse bindings.'''
        
        Observer.__init__(self)
        self._game = game
        self._game.add_observer(self, 'CELL_OFF')
        self._game.add_observer(self, 'CELL_ON')
        
        self._canvas = Canvas(parent, bg=BOARD_BG_COLOR, width=280, height=280)
        self._canvas.grid(row=0, columnspan=3)
        self._canvas.bind("<Button-1>", self.left_button_pressed)
        
        self._regions = {}
        self.__init_regions(self._game)
        self._selection = None
    
    
    def get_selection(self):
        '''Getter of _selection.'''
        
        return self._selection
    
    
    def set_selection(self, sel):
        '''Setter of _selection.'''
        
        self._selection = sel
    
    
    def __init_regions(self, game):
        '''Complete the _regions dictionary.'''
        
        canvas_x = 0
        canvas_y = 0
        for x_index in range(7):
            for y_index in range(7):
                if (x_index, y_index) in game.get_board():
                    self._regions[(x_index, y_index)] =         \
                        Rectangle((canvas_x, canvas_y),         \
                        (canvas_x + BOARD_RECTANGLE_SIZE - 1,   \
                        canvas_y + BOARD_RECTANGLE_SIZE - 1))
                canvas_x += BOARD_RECTANGLE_SIZE
            canvas_x = 0
            canvas_y += BOARD_RECTANGLE_SIZE
    
    
    def left_button_pressed(self, event):
        '''The mouse left button was pressed, so if there's no
        selection, it's created, and if the selection exists,
        attempt to make a movement taking the selection position
        and the current position.'''
        
        pos = self.get_position_from_pixels(event.x, event.y)
        if pos is not None:
            if self.get_selection() is None:
                self.set_selection(pos)
                self.make_selection(pos)
            else:
                self._game.move(self.get_selection(), pos)
                self.clear_selection(self.get_selection())
                self.set_selection(None)
    
    
    def make_selection(self, pos):
        '''A selection was made.'''
        
        self.__selection(pos, BOARD_SEL_COLOR)
    
    
    def clear_selection(self, pos):
        '''No longer selection in the position given.'''
        
        self.__selection(pos, BOARD_BG_COLOR)
    
    
    def __selection(self, pos, color):
        '''Draw the selection rectangle.'''
        
        self._regions[pos].display_on(self._canvas, outline=color)
    
    
    def update(self, aspect, value):
        '''The board organization in the model has changed.'''
        
        if aspect == 'CELL_ON':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_NOT_EMPTY_COLOR)
        elif aspect == 'CELL_OFF':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_EMPTY_COLOR)
    
#.........这里部分代码省略.........
开发者ID:ngarbezza,项目名称:pysenku,代码行数:103,代码来源:pysenku-0.2.py

示例9: Board

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class Board(Tk):
    def __init__(self, width, height, cellSize,player=None,logicBoard=None):
        """

        :param width: largeur du plateau
        :param height: hauteur du plateau
        :param cellSize: largeur des cases
        :param player: joueur
        :param logicBoard: plateau logique (liste de liste)
        """
        Tk.__init__(self)
        self.cellSize = cellSize
        self.guiBoard = Canvas(self, width=width, height=height, bg="bisque")
        self.currentFixedLabel = FixedLabel(self,"CURRENT PLAYER : ",16,0)
        self.currentVariableLabel = VariableLabel(self,18,0,"string")
        self.bluePointsFixedLabel = FixedLabel(self,"BLUE CAPTURES : ",16,2)
        self.bluePointsVariableLabel = VariableLabel(self,18,2,"integer")
        self.redPointsFixedLabel = FixedLabel(self,"RED CAPTURES : ",16,4)
        self.redPointsVariableLabel = VariableLabel(self,18,4,"integer")
        self.logicBoard=logicBoard
        if not(logicBoard):
            self.logicBoard=dr.initBoard(DIMENSION)
        self.player=player
        if not(player):
            self.player=1
        self.hasPlayed=False
        self.hasCaptured=False
        self.guiBoard.bind("<Button -1>", self.bindEvent)
        self.initiateBoard()
        self.guiBoard.grid(rowspan=DIMENSION+1,columnspan=DIMENSION+1,row=0,column=4)

    def getBoard(self):
        return(self.logicBoard)

    def getPlayer(self):
        return(self.player)

    def initiateBoard(self):

        for i in range(DIMENSION):
            for j in range(DIMENSION):
                coordX1 = (i * self.cellSize)
                coordY1 = (j * self.cellSize)
                coordX2 = coordX1 + self.cellSize
                coordY2 = coordY1 + self.cellSize
                color = "white" if i%2 == j%2 else "black"
                cell = self.logicBoard[j][i]
                guiCell=self.draw_rectangle(coordX1, coordY1, coordX2, coordY2, color, "r"+str(i)+str(j))
                if cell !=0:
                    pawnColor = "red" if cell > 0 else "blue"
                    pawn=self.draw_circle(coordX1, coordY1, coordX2, coordY2, pawnColor, "c"+str(i)+str(j),pawnColor)

    def draw_rectangle(self,coordX1,coordY1,coordX2,coordY2,color,tags):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :return: Id du rectangle
        """
        self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags)
        return(self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags))
    def draw_circle(self, coordX1, coordY1, coordX2,coordY2, color, tags,outline):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :param outline: couleur du bord du cercle
        :return: Id du cercle
        """
        return(self.guiBoard.create_oval(coordX1,coordY1,coordX2,coordY2,fill=color,outline=outline,tags=tags))

    def findLength(self,i,j,ancientSelectedCellTags):

        """

        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonne
        :param ancientSelectedCellTags: tags de la case anciennement selectionnée
        :return: longueur
        """
        departJ=int(ancientSelectedCellTags[0][1])
        departI=int(ancientSelectedCellTags[0][2])
        length=None
        if(departI!=i):
            isDiago=abs(j-departJ)/abs(i-departI)

            if(isDiago==1):#la case d'arrivée se trouve sur la diagonale
                length=( ((j-departJ)**2) + ((i-departI)**2) )**(1/2) #recherche de l'hypothenuse
                length/=(2)**(1/2) #divisé par racine de 2 car l'hypothenuse d'un triangle avec 2 coté de longueur 1 = racine de 2
        return(length)

    def findDirection(self,i,j,ancientSelectedCellTags):
#.........这里部分代码省略.........
开发者ID:malikfassi,项目名称:draughts,代码行数:103,代码来源:draughtsGUI.py

示例10: loop

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
			else:
				xplus = x+1;
			if y == 99:
				yplus = 0;
			else:
				yplus = y+1;
			neighbours = board[xplus][yplus] + board[xplus][y] + board[xplus][yminus] + board[x][yplus] + board[x][yminus] + board[xminus][yplus] + board[xminus][y] + board[xminus][yminus];
			if neighbours == 3:
				nboard[x][y] = 1;
			elif neighbours != 2:
				nboard[x][y] = 0;
			else:
				nboard[x][y] = board[x][y]
	board, nboard = nboard, board;

def loop(*args):
	if state:
		makeTurn();
		redraw();
		canvas.after(10, func=loop);

def switchState(*args):
	global state;
	state = not state;
	if state:
		loop();

canvas.bind("<Button-1>",diviveIntervention);
canvas.bind("<Button-3>",switchState);
canvas.mainloop();
开发者ID:IHumonen,项目名称:d16,代码行数:32,代码来源:i_am_alife_beware.py

示例11: take_screenshot_crop

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
def take_screenshot_crop(path):
    pimage = _r.take_screenshot()

    _, _, width, height = pimage.getbbox()

    displays = _r.get_display_monitors()
    leftmost, topmost = 0, 0
    for d in displays:
        if d[0] < leftmost:
            leftmost = d[0]
        if d[1] < topmost:
            topmost = d[1]

    root = Tk()  # Creates a Tkinter window
    root.overrideredirect(True)  # Makes the window borderless
    root.geometry("{0}x{1}+{2}+{3}".format(width, height, leftmost, topmost))  # window size = screenshot size
    root.config(cursor="crosshair")  # Sets the cursor to a crosshair

    pimage_tk = ImageTk.PhotoImage(pimage)  # Converts the PIL.Image into a Tkinter compatible PhotoImage

    can = Canvas(root, width=width, height=height)  # Creates a canvas object on the window
    can.pack()
    can.create_image((0, 0), image=pimage_tk, anchor="nw")  # Draws the screenshot onto the canvas

    # This class holds some information about the drawn rectangle
    class CanInfo:
        rect = None
        startx, starty = 0, 0

    # Stores the starting position of the drawn rectangle in the CanInfo class
    def xy(event):
        CanInfo.startx, CanInfo.starty = event.x, event.y

    # Redraws the rectangle when the cursor has been moved
    def capture_motion(event):
        can.delete(CanInfo.rect)
        CanInfo.rect = can.create_rectangle(CanInfo.startx, CanInfo.starty, event.x, event.y)

    # Cancels screen capture
    def cancel(event):
        if event.keycode == 27:  # cancel when pressing ESC
            root.destroy()

    # Saves the image when the user releases the left mouse button
    def save_img(event):
        startx, starty = CanInfo.startx, CanInfo.starty
        endx, endy = event.x, event.y

        # Puts the starting point in the upper left and the ending point in the lower right corner of the rectangle
        if startx > endx:
            startx, endx = endx, startx
        if starty > endy:
            starty, endy = endy, starty

        crop_image = pimage.crop((startx, starty, endx, endy))
        crop_image.save(path, "PNG")
        root.destroy()  # Closes the Tkinter window

    # Binds mouse actions to the functions defined above
    can.bind("<KeyPress>", cancel)
    can.bind("<Button-1>", xy)
    can.bind("<B1-Motion>", capture_motion)
    can.bind("<ButtonRelease-1>", save_img)

    can.focus_force() # Force focus of capture screen
    root.mainloop()  # Shows the Tk window and loops until it is closed
开发者ID:instantshare,项目名称:instantshare,代码行数:68,代码来源:windows_tk.py

示例12: QuickHull

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [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

示例13: simulation_canvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
def simulation_canvas  (parent,**config):
    global the_canvas
    the_canvas = Canvas(parent,**config)
    the_canvas.bind("<ButtonRelease>", lambda event : model.mouse_click(event.x,event.y))
    return the_canvas
开发者ID:Yangsilu,项目名称:database,代码行数:7,代码来源:controller.py

示例14: Tk

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
    mouseI.parentOn(cx,cy)
    mouseI.draw()
        

"""
Global Variables, main script
"""
#global variables
WIDTH, HEIGHT = 640, 480
mouseDown = 0

#window initialization, more declarations
gwindow = Tk()
canvas = Canvas(gwindow, width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
mouseI = GraphWindow(100,100,25,25,"blue")
mouseI.setCanvas(canvas)
iwindow = Tk()
canvasi = Canvas(iwindow, width=WIDTH, height=HEIGHT, bg="#000000")
canvasi.pack()
mouseI.addInfoWindow(canvasi)

#bind in mouse handlers
canvas.bind("<Button-1>", mouseDown)
canvas.bind("<ButtonRelease-1>", mouseUp)
canvas.bind("<B1-Motion>", mouseClick)   

#initial draw and start loop
mouseI.draw()
mainloop()
开发者ID:ksjp,项目名称:interactiveGraph,代码行数:32,代码来源:interactiveGraph.py

示例15: Scene

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import bind [as 别名]
class Scene(object):
    def __init__(self, master, device, mouse_tracking=False):
        self.master = master
        self.device = device
        self.frame = tk.Frame(master)
        self.feedbackButton = tk.Button(
            self.frame,
            text="Feedback window",
            width=25,
            command=self.open_feedback
        )
        self.feedbackButton.pack()
        self.explore_canvas = Canvas(master, width=500, height=500)
        self.explore_canvas.pack()

        if mouse_tracking:
            self.explore_canvas.bind(
                '<Motion>', lambda event, device=device: motion(event, device))

        self.enable_position_feedback()
        self.network_drawings = []

        self.frame.pack()
        self.app = None
        self.update()

    def activate_key_listening(self, listener):
        # Will focus frame, needed for key binding
        self.explore_canvas.bind(
            "<Button-1>",
            lambda event,
            frame=self.explore_canvas: focus(event, frame)
        )
        self.explore_canvas.bind(
            "<Key>",
            lambda event: listener.update_pressed_key(str(event.char))
        )

    def desactivate_key_listening(self):
        self.explore_canvas.unbind("<Button-1>")
        self.explore_canvas.unbind("<Key>")

    def enable_position_feedback(self):
        self.device_cursor = self.explore_canvas.create_oval(
            self.device.position.x - 2.5, self.device.position.y - 2.5,
            self.device.position.x + 2.5, self.device.position.y + 2.5)

    def draw_network(self, network):
        self.explore_canvas.delete('all')
        self.enable_position_feedback()
        for node in network.nodes:
            pos_x = node.x - 5
            pos_y = node.y - 5
            self.explore_canvas.create_oval(
                pos_x, pos_y, pos_x + 10, pos_y + 10, fill="blue")
        for link in network.links:
            pt_a = link.first
            pt_b = link.sec
            self.explore_canvas.create_line(
                pt_a.x, pt_a.y, pt_b.x, pt_b.y)

    def update(self):
        coords = self.explore_canvas.coords(self.device_cursor)
        if len(coords) <= 3:
            self.master.after(50, self.update)
            return
        center = ((coords[0] + coords[2]) / 2, (coords[1] + coords[3]) / 2)
        self.explore_canvas.move(
            self.device_cursor,
            self.device.position.x - center[0],
            self.device.position.y - center[1])
        if self.app and not self.app.closed:
            self.app.update()
        self.master.after(50, self.update)

    def open_feedback(self):
        self.feedbackWindow = tk.Toplevel(self.master)
        self.app = Feedback(self.feedbackWindow, self.device)
开发者ID:poussin87,项目名称:haptiq,代码行数:80,代码来源:view.py


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