Reputation: 189
I created a canvas widget and drew a line that goes from the top left to the bottom right corner. Now if I resize my window the line stays in place and does not strech to go from the top left to bottom right corner. How can I draw stuff in a canvas and make it strech as the window is resized? Basically give anything in a canvas a relative size and position.
from tkinter import *
root = Tk()
root.geometry("400x400")
c = Canvas(root)
c.pack(fill=BOTH, expand=1)
c.create_line(0, 0, 400, 400)
root.mainloop()
Upvotes: 2
Views: 856
Reputation: 385870
You will have to detect the canvas being resized and adjust the coordinates yourself. Binding to <Configure>
is a convenient way to have a function called whenever the widget changes size.
Here's a simplistic example that takes advantage of the fact that you only have one item. If there were dozens of items, some with relative coordinates and some without, you would have to do something more elaborate.
import tkinter as tk
def redraw(event):
c.coords(item, 0, 0, event.width, event.height)
root = tk.Tk()
root.geometry("400x400")
c = tk.Canvas(root)
c.pack(fill="both", expand=True)
c.bind("<Configure>", redraw)
item = c.create_line(0,0,400,400)
root.mainloop()
Upvotes: 2