Отредактировано для ответа на комментарий.
Для холста предполагается, что canvas = tk.Canvas(...)
The Top Left is (0,0),
the Bottom Right is (canvas.winfo_width(), canvas.winfo_height())
Другие соответствующие точки можно рассчитать по ширине и высоте.Если размер холста изменяется в процессе его использования, необходимо пересчитать точки (кроме 0,0).
Я не могу найти ничего встроенного, чтобы «привязать» объекты к углам, средним точкам и т. Д... Приведенный ниже код либо выполняет функции обёртки точки компаса для привязки элементов к заранее определенным местам.Или функция привязки в любом месте холста, основанная на пропорциях.Обратный вызов on_resize необходим, даже если Canvas делает, не изменяет размер, так как объекты id часто указываются до рисования холста.
import tkinter as tk
root = tk.Tk()
root.geometry('400x200')
canvas = tk.Canvas(root)
# canvas changes size with the root.
canvas.grid(sticky=tk.N+tk.S+tk.E+tk.W)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
def snap(parent, id, x_fact, y_fact, anchor = tk.CENTER ):
""" parent - tk.Canvas widget
id canvas object id
x_fact & y_fact: floats 0. to 1. 0 is N/W, 1. is S/E
anchor is the anchor point on the object.
"""
def on_resize( ev ):
""" Callback for Configure event """
x = int( ev.width * x_fact )
y = int( ev.height * y_fact )
parent.coords( id, x, y )
parent.itemconfigure( id, anchor = anchor )
x = int( parent.winfo_width() * x_fact )
y = int( parent.winfo_height() * y_fact )
parent.coords( id, x, y )
parent.bind( '<Configure>', on_resize, add='+' )
return id
def snap_to( x_fact, y_fact, anchor = tk.CENTER ):
""" Returns a function which snaps to a named location. """
def func( parent, id ):
return snap( parent, id, x_fact, y_fact, anchor )
return func
snap_NW = snap_to( 0, 0, tk.NW )
snap_N = snap_to( 0.5, 0 , tk.N )
snap_NE = snap_to( 1, 0, tk.NE )
snap_W = snap_to( 0, 0.5, tk.W )
snap_C = snap_to( 0.5, 0.5, tk.CENTER )
snap_E = snap_to( 1, 0.5, tk.E )
snap_SW = snap_to( 0, 1, tk.SW )
snap_S = snap_to( 0.5, 1, tk.S )
snap_SE = snap_to( 1, 1, tk.SE )
test0 = canvas.create_text( 0, 0, text=' SE ')
snap_SE(canvas, test0)
test1 = snap_E(canvas, canvas.create_text( 0, 0, text=' East '))
snap_N(canvas, canvas.create_text( 0, 0, text=' North '))
snap_NW(canvas, canvas.create_text( 0, 0, text=' NW '))
snap_NE(canvas, canvas.create_text( 0, 0, text=' NE '))
snap_W(canvas, canvas.create_text( 0, 0, text=' West '))
snap_C(canvas, canvas.create_text( 0, 0, text=' Centre '))
snap_SW(canvas, canvas.create_text( 0, 0, text=' SW '))
snap_S(canvas, canvas.create_text( 0, 0, text=' South '))
snap( canvas,
canvas.create_text( 0, 0, text=' Quarters '),
0.25, 0.25)
root.mainloop()
Это то, что вы имели в виду?
Ниже приведено альтернативное использование вышеуказанного с использованием snap
, а не snap_to
.
# Named constants for tuples of function parameters.
CEN = ( 0.5, 0.5, tk.CENTER ) # tk.CENTER is the default and could be omitted
SE = ( 1., 1., tk.SE )
# Call snap with the constants setting the three last parameters.
snap( canvas, canvas.create_text( 0, 0, text=' Centre '), *CEN )
snap( canvas, canvas.create_text( 0, 0, text=' SE '), *SE )