调整 Tkinter 大小时的行位置 window

position of line when resizing Tkinter window

以下代码:

from tkinter import *
root=Tk()
for x in range(10):
    for y in range(10):
        canvas=Canvas(root, width='15',height='15',highlightthickness=0,bg='red')                      
        canvas.create_line(canvas.winfo_x(),canvas.winfo_y(),canvas.winfo_x()+15,canvas.winfo_y()+15,width=2,fill='black')
        canvas.grid(row=y,column=x,sticky='NESW')
for x in range(10):
    for y in range(10):
        root.columnconfigure(x,weight=1)
        root.rowconfigure(y,weight=1)
root.mainloop()

生成 this,这是一个 10 x 10 的网格,其中填充了 canvases;每个 canvas.

从左上角到右下角都有一条线

当我调整 window 大小时,canvas 小部件正确调整大小,但线条保持其形状 like this。线条需要根据 window/widget 大小进行调整。

问题的核心是线条是使用小部件左上角的坐标绘制的,并在每个方向上扩展了 15 个像素。有没有办法获取小部件右下角的坐标,以便线条可以动态改变它们的形状,或者其他一些保持线条形状的方法,相对于小部件?

您可以使用 winfo_widthwinfo_height 方法获取任何小部件的当前宽度和高度。如果您绑定到 <Configure> 方法以在 canvas 更改大小时进行跟踪,则事件对象具有 widthheight 属性。

例如:

from tkinter import *

def redraw_line(event):
    width = event.width
    height = event.height
    canvas = event.widget
    canvas.coords("diagonal", 0, 0, width, height)

root=Tk()
for x in range(10):
    for y in range(10):
        canvas=Canvas(root, width='15',height='15',highlightthickness=0,bg='red')                      
        canvas.bind("<Configure>", redraw_line)
        # coordinates are irrelevant; they will change as soon as
        # the widget is mapped to the screen.
        canvas.create_line(0,0,0,0, tags=("diagonal",))
        canvas.grid(row=y,column=x,sticky='NESW')

for x in range(10):
    for y in range(10):
        root.columnconfigure(x,weight=1)
        root.rowconfigure(y,weight=1)


root.mainloop()