Tkinter Canvas画布控件定位布局

import tkinter as tk

# PARAMETERS

SIZE = 800
SQUARES = 10


def draw_board():
    i = 0
    while i < SIZE:
        canvas.create_line(0, i, SIZE, i)
        canvas.create_line(i, 0, i, SIZE)
        i += SIZE / SQUARES


def place_pawn(x, y, color):
    pos = [(x-0.5)*SIZE/SQUARES, (y-0.5)*SIZE/SQUARES]
    pawn_colors = {'blue': '#104E8B', 'green': '#008B45'}
    canvas.create_text(pos, text='P', font=('Times', 30), fill=pawn_colors[color])


root = tk.Tk()
root.minsize(SIZE, SIZE)
canvas = tk.Canvas(root, width=SIZE, height=SIZE)
canvas.pack()
draw_board()
place_pawn(2, 3, 'blue')
place_pawn(8, 6, 'blue')
place_pawn(1, 1, 'blue')
place_pawn(9, 9, 'green')
place_pawn(9, 1, 'green')

root.mainloop()

评论