I’m a first timer at tkinter(python) and what I want to do is to make a line of text stay on the same coords ratio on the canvas. For example, I want a line of text to stay in the middle. Is there any tkinter text parameters that make it stay in a certain ratio without running a while loop? I want minimal time complexity.
Advertisement
Answer
Your GUI can have a function bound to the Canvas <Configure>
event that fires whenever the Canvas changes size. A simple example below.
There is also a Canvas.scale
method which will change the location and size of canvas objects. Text may move but will not change size.
import tkinter as tk root = tk.Tk() # Create a canvas that will change size with the root window. canvas = tk.Canvas( root, width = 600, height = 400, borderwidth = 2, relief = tk.SOLID ) canvas.grid( sticky = 'nsew', padx = 5, pady = 5 ) root.grid_columnconfigure( 0, weight = 1 ) root.grid_rowconfigure( 0, weight = 1 ) text = canvas.create_text( 50, 50, text = 'Test Text' ) def on_canvas_config( event ): """ This is bound to the canvas <Configure> event. It executes when the canvas changes size. The event is an object that contains the new width and height. """ x = max( 25, event.width // 2 ) # x >= 25 y = max( 12, event.height // 8 ) # y >= 12 canvas.coords( text, x, y ) # Set the canvas coordinates canvas.bind( '<Configure>', on_canvas_config ) root.mainloop()
The on_canvas_configure
function can be written to amend the coords of any objects in the Canvas to meet your requirements. I’ve never tried to use the Canvas.scale
method but this may be worth exploring if there are many objects to reposition on the canvas.