簡體   English   中英

是否有 Python tkinter function 在 canvas 小部件上按一定比例繪制圖形坐標?

[英]Is there a Python tkinter function that makes a drawing’s coords on a certain ratio on the canvas widget?

我是 tkinter(python) 的初學者,我想做的是讓一行文本在 canvas 上保持相同的坐標比。例如,我想要一行文本留在中間。 是否有任何 tkinter 文本參數使其在不運行 while 循環的情況下保持一定比例? 我想要最小的時間復雜度。

您的 GUI 可以將 function 綁定到 Canvas <Configure>事件,該事件會在 Canvas 更改大小時觸發。 下面是一個簡單的例子。

還有一個Canvas.scale方法會改變 canvas 對象的位置和大小。 文本可能會移動但不會改變大小。

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 function 來修改Canvas 中任何對象的坐標以滿足您的要求。 我從未嘗試過使用Canvas.scale方法,但如果有許多對象要在 canvas 上重新定位,這可能值得探索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM