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


Python Canvas.focus_set方法代码示例

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


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

示例1: simulation_canvas

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

示例2: text_canvas

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
class text_canvas(Frame):

    def __init__(self, parent, font_size, input_handler, filename):
        Frame.__init__(self, parent)
        self.parent = parent
        self.text_font = tkFont.Font(
            family='Monaco', size=font_size, weight='bold'
        )
        self.filename = filename
        self.cheight, self.cwidth = font_size, self.text_font.measure('c')
        self.line_num_spacing = 50
        self.line_height = (
            (self.winfo_screenheight() - self.cheight)//(self.cheight + 2) - 4
        )
        self.init_UI(input_handler)

    def init_UI(self, input_handler):
        self.parent.title('')
        self.pack(fill=BOTH, expand=1)
        self.init_canvas(input_handler)

    def get_dimensions(self):
        """
        Getting the dimensions might be helpful
        for plugin writers
        """
        return {
            'cheight': self.cheight,
            'cwidth': self.cwidth,
            'line_num_spacing': self.line_num_spacing,
            'line_height': self.line_height,
            'screen_width': self.winfo_screenwidth(),
            'screen_height': self.winfo_screenheight()
        }

    def init_canvas(self, input_handler):
        self.canvas = Canvas(
            self, highlightthickness=0, width=self.winfo_screenwidth(),
            height=self.winfo_screenheight(), bg=options['background_color']
        )
        self.canvas.pack()
        self.canvas.focus_set()
        self.bind_events(input_handler)

    def clear_all(self):
        self.canvas.delete('all')

    def get_line_height(self):
        """
        return number of lines per page
        """
        return self.line_height

    def get_grid_y(self, y):
        """
        return character height * y
        in addition distane of the spaces inbetwen
        """
        return self.cheight * y + (y * 2)

    def write_line_grid(self, y, line):
        """
        Write to line of text on grid using tokens passed in
        """
        for token in line:
            self.write_text_grid(token[0], y, token[1], token[2])

    def write_text_grid(self, x, y, text, color=options['text_color']):
        """
        Write text to x, y location on grid
        """
        x_val = self.cwidth * x + self.line_num_spacing
        y_val = self.cheight * y + (y * 2)  # 2 pixel spacing between each line
        self.canvas.create_text(
            x_val, y_val, anchor='nw', text=text,
            font=self.text_font, fill=color
        )

    def write_status_line(
        self, text, textcolor=options['status_text_color'],
        backgroundcolor=options['status_background_color']
    ):
        """
        Writen a line of text to status line
        this function could take in different data if desired
        """
        y = self.line_height + 1
        self.canvas.create_rectangle(
            0, self.cheight * y + (y * 2), self.winfo_screenwidth(),
            self.cheight * y + (y * 2) + self.cheight + 4,
            fill=backgroundcolor, outline=backgroundcolor
        )
        self.write_text_grid(0, self.line_height + 1, text, textcolor)

    def draw_highlight_grid(
        self, y, x1, x2,
        highlightcolor=options['text_highlight_color']
    ):
        """
        Draw highlights onto text canvas
#.........这里部分代码省略.........
开发者ID:m45t3r,项目名称:shim,代码行数:103,代码来源:text_canvas.py

示例3: SkylineUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
class SkylineUI(Frame):
    """
    GUI for the skyline game
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

    def __initUI(self):
        self.parent.title("Skyline")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Reset",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_game()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)


    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in range(self.game.size + 3):
            color = "blue" if i % 6 == 0 else "gray"
            if i == 1 or i == self.game.size + 1:
                color = "red"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)


    def __draw_game(self):
        
        self.canvas.delete("numbers")
        for i in range(0, self.game.size):
            for j in range(0, self.game.size):
                answer = self.game.board[i][j]
                #if answer != 0:
                x = MARGIN + (j+1) * SIDE + SIDE / 2
                y = MARGIN + (i+1) * SIDE + SIDE / 2
                original = self.game.board_object.empty_board[i][j]
                color = "black" if answer == 0 else "sea green"
                self.canvas.create_text(
                    x, y, text=answer, tags="numbers", fill=color
                )
        self.__draw_hints()


    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")
        self.__draw_game()


    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                outline="red", tags="cursor"
            )


    def __cell_clicked(self, event):
        if self.game.hasWon:
            return
        x, y = event.x, event.y
        if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
            self.canvas.focus_set()

            # get row and col numbers from x,y coordinates
            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

#.........这里部分代码省略.........
开发者ID:SebWitt,项目名称:skyline,代码行数:103,代码来源:UI.py

示例4: AppLogic

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
class AppLogic(threading.Thread):

    def __init__(self, tk_root):
        self.root = tk_root
        threading.Thread.__init__(self)
        self.turn = 0
        self.update = False
        self.x = -1
        self.y = -1
        self.start()
    
    def run(self):
        self.game_gui = Canvas(self.root, width=600, height=600, background='green')
        self.game_gui.bind("<Button-1>", self.click)
        self.game_gui.focus_set()
        self.game_gui.bind("<Key>", self.key)
        self.game_gui.pack()
        for i in range(1, 8):
            self.game_gui.create_line(0, i*75, 600, i*75)
            self.game_gui.create_line(i*75, 0, i*75, 600)
        
        self.pieces = []
        for i in range(8):
            self.pieces.append([])
            for j in range(8):
                self.pieces[i].append(self.game_gui.create_oval(i*75+5, j*75+5, (i+1)*75-5, (j+1)*75-5, fill="green", outline="green"))
        
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.resizable(0,0)
        self.running = True
        config = EvaluateConfig()
        tf_util.update_memory(config.gpu_mem_fraction)
        AIPlayer.create_if_nonexistant(config)
        self.game = Othello()
        if(random() > 0.5):
            self.human = 1
        else:
            self.human = -1
        
        ai = create_player(config.model_1, config)
        #print("You are playing against", config.model_1)
        #print("Playing games with %d simulations per move" % config.game.simulation_num_per_move)
        self.side = -1
        self.draw_board()
        self.value = ai.evaluate(self.game, self.side)
        while self.running and not self.game.game_over():
            #play move
            if self.side != self.human:
                self.value = ai.evaluate(self.game, self.side)
                self.root.title("Othello (Thinking of Move) Current Value: %0.2f (1 white wins, -1 black wins)" % self.value)
                self.root.config(cursor="wait")
                t = ai.pick_move(self.game, self.side)
                self.game.play_move(t[0], t[1], self.side)
                self.draw_board()
                self.side *= -1
                self.value = ai.evaluate(self.game, self.side)
            else:
                if len(self.game.possible_moves(self.side)) == 0:
                    self.side *= -1
                    continue
                if self.side == -1:
                    color = "black"
                else:
                    color = "white"
                self.root.title("Othello (Play as %s) Current Value: %0.2f (1 white wins, -1 black wins)" % (color, self.value))
                self.root.config(cursor="")
                if self.update:
                    self.update = False
                    if (self.x, self.y) in self.game.possible_moves(self.side):
                        self.game.play_move(self.x, self.y, self.side)
                        self.draw_board()
                        self.side *= -1
            time.sleep(0.01)
        self.root.config(cursor="")
        if self.human == self.game.get_winner():
            self.root.title("Othello (You Win!)")
        elif self.game.get_winner() == 0:
            self.root.title("Othello (Its a draw!)")
        else:
            self.root.title("Othello (You Lose!)")

    def key(self, event):
        if event.char == "z":
            self.human *= -1

    def click(self, event):
        self.game_gui.focus_set()
        if self.human == self.side and not self.update:
            if self.x != event.x//75 or self.y != event.y//75:
                self.update = True
                self.x = event.x//75
                self.y = event.y//75
    
    def on_closing(self):
        self.running = False
        self.root.destroy()

    def draw_board(self):    
        for i in range(8):
            for j in range(8):
#.........这里部分代码省略.........
开发者ID:1715509415,项目名称:alpha_zero_othello,代码行数:103,代码来源:play_game.py

示例5: PhotoImage

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
    pos = my_hero.findPosition(my_coord)
    try:
        if my_coord[pos-1].get("t") == 0 and pos % 10 > 0:
            my_coord[pos]["h"] = 0
            my_coord[pos-1]["h"] = 1
            my_hero.charType = PhotoImage(file = "assets/hero-left.png")
    except:
        pass
    my_map.SetTiles(canvas, my_coord, my_hero)
    
def moveTheCharRight(event):
    global my_coord
    global my_hero
    pos = my_hero.findPosition(my_coord)
    try:
        if my_coord[pos+1].get("t") == 0 and pos % 10 < 9:
            my_coord[pos]["h"] = 0
            my_coord[pos+1]["h"] = 1
            my_hero.charType = PhotoImage(file = "assets/hero-right.png")
    except:
        pass
    my_map.SetTiles(canvas, my_coord, my_hero)


canvas.bind("s", moveTheCharDown)
canvas.bind("w", moveTheCharUp)
canvas.bind("a", moveTheCharLeft)
canvas.bind("d", moveTheCharRight)
canvas.pack()
canvas.focus_set()
root.mainloop()
开发者ID:greenfox-velox,项目名称:attilakrupl,代码行数:33,代码来源:main.py

示例6: SudokuUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
class SudokuUI(Frame):
    """
    The Tkinter UI, responsible for displaying the UI.
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

        def __initUI(self):
            self.parent.title("Sudoku")
            self.pack(fill=BOTH, expand=1)  # Use all available space
            self.canvas = Canvas(self, width=WIDTH, heigh=HEIGHT)
            self.canvas.pack(fill=BOTH, side=TOP)  # Pull board to top of frame
            clear_button = Button(self, text="Clear answers", command=self.__clear_answers)
            clear_button.pack(fill=BOTH, side=BOTTOM)

            self.__draw_grid()
            self.__draw_puzzle()

            self.canvas.bind("<Button-1>", self.__cell_clicked)
            self.canvas.bind("<Key>", self.__key_pressed)

        def __draw_grid(self):
            """
            Draws grid divided with blue lines into 3 x 3 grid
            :return:
            """
            for i in range(10):
                color = 'blue' if i % 3 == 0 else "gray"

                x0 = MARGIN + i * SIDE
                y0 = MARGIN
                x1 = MARGIN + i * SIDE
                y1 = HEIGHT - MARGIN
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

                x0 = MARGIN
                y0 = MARGIN + i * SIDE
                x1 = WIDTH - MARGIN
                y1 = MARGIN + i * SIDE
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

        def __draw_puzzle(self):
            self.canvas.delete("numbers")
            for i in xrange(9):
                for j in xrange(9):
                    answer = self.game.puzzle[i][j]
                    if answer != 0:
                        x = MARGIN + j * SIDE + SIDE / 2
                        y = MARGIN + i * SIDE + SIDE / 2
                        original = self.game.start_puzzle[i][j]
                        color = "black" if answer == original else "sea green"
                        self.canvas.create_text(x, y, text=answer, tags="number", fill=color)

        def __clear_answers(self):
            self.game.start()
            self.canvas.delete("victory")
            self.__draw_puzze()

        def __cell_clicked(self, event):  # event has x, y coords of mouse click
            if self.game.game_over:
                return

            x, y = event.x, event.y
            if (MARGIN < x < WIDTH - MARGIN) and (MARGIN < Y < HEIGHT - MARGIN):
                self.canvas.focus_set()

                # get row and col numbers from x, y coords
                row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

                # if cell already selected then deselect it
                if (row, col) == (self.row, self.col):
                    self.row, self.col = -1, -1  # outside the grid
                elif self.game.puzzle[row][col] == 0:
                    self.row, self.col = row, col

            self.__draw_cursor()

        def __draw_cursor(self):
            self.canvas.delete("cursor")
            if self.row >= 0 and self.col >= 0:
                x0 = MARGIN + self.col * SIDE + 1
                y0 = MARGIN + self.row * SIDE + 1
                x1 = MARGIN + (self.col + 1) * SIDE - 1
                y1 = MARGIN + (self.row + 1) * SIDE - 1
                self.canvas.create_rectangle(
                    x0, y0, x1, y1,
                    outline ="red", tags ="cursor"
                )
开发者ID:stevegleds,项目名称:my-project-ideas,代码行数:96,代码来源:tkintertesting.py

示例7: __init__

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

#.........这里部分代码省略.........
                (nx, ny) = (x-1, y)
            elif act == Action.right:
                (nx, ny) = (x+1, y)
            real_pos = (
                max(0, min(self.width-1, nx)),
                max(0, min(self.height-1, ny)),
            )
            
            self.player_pos = real_pos
            pen = 0 if real_pos == (nx, ny) else -1
            rew += pen
        elif act == Action.pick and self.state == State.start:
            if self.obj_pos == self.player_pos:
                self.state = State.picked
                if self.first_pick:
                    self.first_pick = False
                    rew += 1
                if (not self.task_type & TaskType.put):
                    self.state = State.end
        elif act == Action.put and self.state == State.picked:
            if self.mark_pos == self.player_pos:
                self.state = State.end
                rew += 1
            else:
                self.state = State.start
                self.obj_pos = self.player_pos

        if self.state == State.end:
            rew += 5
        return rew

    def render(self):
        # clear canvas
        self.draw.rectangle((0, 0, self.frame_width, self.frame_height),
                            fill='black')

        # draw obj
        if self.obj_pos and self.state == State.start:
            px, py = self._get_frame_pos(self.obj_pos)
            self.draw.rectangle((px - 2, py - 2, px + 2, py + 2), fill='green')
            
        # draw mark
        if self.mark_pos:
            px, py = self._get_frame_pos(self.mark_pos)
            self.draw.rectangle((px - 2, py - 2, px + 2, py + 2), outline='white')

        # draw player
        px, py = self._get_frame_pos(self.player_pos)
        loc = (px - 2, py - 2, px + 2, py + 2)
        if self.state == State.picked:
            self.draw.ellipse(loc, fill=(0, 255, 255, 0))
        else:
            self.draw.ellipse(loc, fill='blue')

        if self.show_gui:
            gui_img = self.image.resize((self.frame_width * self.gui_amp,
                                         self.frame_height * self.gui_amp))
            self.pi = ImageTk.PhotoImage(gui_img)
            canvas_img = self.canvas.create_image(0, 0, anchor=NW,
                                                  image=self.pi)
            # self.canvas.create_text((self.width*self.gui_amp-20, 5), 
                                    # fill='white', text=str(self.))

            if not self.human_play:
                self.tk.update()

    def get_bitmap(self):
        arr = np.array(self.image.getdata()).reshape(self.image_shape)
        return arr.astype('float32') / 256.0

    def gui_step(self):
        if self.last_act is not None:
            rew = self.step(self.last_act)
            self.last_act = None
        else:
            rew = self.step(None)
        if abs(rew) > 1e-9:
            print('Get reward = %.2f' % rew)
        self.render()
        self.tk.after(1000//self.FPS, self.gui_step)

    def gui_start(self):
        self.canvas.bind("<Key>", self.gui_onkey)
        self.canvas.focus_set()
        self.tk.after(1000//self.FPS, self.gui_step)
        self.tk.mainloop()

    def gui_onkey(self, event):
        if event.keycode == 111 or event.keycode == 8320768:
            self.last_act = Action.up
        elif event.keycode == 116 or event.keycode == 8255233:
            self.last_act = Action.down
        elif event.keycode == 113 or event.keycode == 8124162:
            self.last_act = Action.left
        elif event.keycode == 114 or event.keycode == 8189699:
            self.last_act = Action.right
        elif event.keycode == 53 or event.keycode == 458872:
            self.last_act = Action.pick
        elif event.keycode == 52 or event.keycode == 393338:
            self.last_act = Action.put
开发者ID:kevin00036,项目名称:gym,代码行数:104,代码来源:game.py

示例8: SudokuUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import focus_set [as 别名]
class SudokuUI(Frame):
    '''
        The class responsible to create the Sudoku UI and interact with the User and accept the inputs from the User and
        run the game logic to verify the inputs of the user has led the user to win or loose the game...
    '''
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        super(SudokuUI, self).__init__()


        self.row = 0
        self.column = 0

        self.__initUI()

    def __initUI(self):
        assert isinstance(self.parent, Tk)
        self.parent.title('Sudoku')
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        self.clear_button = Button(self, text='Clear Answers', command=self.__clear_answers)
        self.clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()

        self.canvas.bind('<Button-1>', self.__cell_clicked)
        self.canvas.bind('<Key>', self.__key_pressed)

    def __draw_grid(self):
        '''
            Draws the 3x3 grid separated by blue lines
        '''
        for i in range(10):
            color = 'blue' if i%3 == 0 else 'grey'
            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_puzzle(self):
        self.canvas.delete('numbers')
        for i in range(9):
            for j in range(9):
                answer = self.game.puzzle[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    original = self.game.start_game[i][j]
                    color = 'black' if answer == original else 'sea green'
                    self.canvas.create_text(x, y, text=answer, tags='numbers', fill=color)

    def __clear_answers(self):
        self.game.start()
        self.canvas.delete('victory')
        self.__draw_puzzle()

    def __cell_clicked(self, event):
        if self.game.game_over:
            return

        x, y = event.x, event.y
        if(MARGIN < x < WIDTH - MARGIN and MARGIN < y <HEIGHT - MARGIN):
            self.canvas.focus_set()

            row, col = (y - MARGIN)/SIDE, (x - MARGIN)/SIDE
            if (row, col) == (self.row, self.column):
                self.row, self.column = -1, -1
            else:
                self.row, self.column = row, col

        self.__draw_cursor()

    def __draw_cursor(self):
        self.canvas.delete('cursor')
        if self.row >= 0 and self.column >= 0:
            x0 = MARGIN + self.column * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.column + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1

            self.canvas.create_rectangle(x0, y0, x1, y1, outline='red', tags='cursor')

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.column >= 0 and event.char in '1234567890':
            self.game.puzzle[int(self.row)][int(self.column)] = int(event.char)
            self.row, self.column = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
#.........这里部分代码省略.........
开发者ID:sambitpritam,项目名称:assesments,代码行数:103,代码来源:sudoku.py

示例9: __init__

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