是否有一个Python tkinter函数,使绘图的坐标在画布小部件上的一定比例?



我是第一次使用tkinter(python),我想做的是使一行文本保持在画布上相同的坐标比率。例如,我希望一行文本留在中间。是否有任何其他文本参数,使其保持在一定的比例,而不运行while循环?我想要最小的时间复杂度

你的GUI可以有一个绑定到Canvas<Configure>事件的函数,当Canvas改变大小时触发。下面是一个简单的例子。

还有一个Canvas.scale方法,它将改变画布对象的位置和大小。文字可以移动,但不会改变大小。

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()

可以编写on_canvas_configure函数来修改Canvas中任何对象的坐标以满足您的要求。我从来没有尝试过使用Canvas.scale方法,但这可能值得探索,如果有许多对象在画布上重新定位。

最新更新