【问题标题】:When and why do I need to change a window coordinate to a canvas coordinate?何时以及为什么需要将窗口坐标更改为画布坐标?
【发布时间】:2020-11-21 15:55:09
【问题描述】:

我试图通过给画布一个回调来查看窗口坐标和画布坐标之间的区别,该回调会在两种类型中打印鼠标单击的坐标。我希望这两种类型的坐标具有不同的值,但事实并非如此。另外,我尝试将窗口坐标传递给find_closest 方法,正如documentation 中所述,该方法接受画布坐标,并且没有错误。

import tkinter as tk

def callback(event):
    canvas = event.widget
    print()
    print("Window x-coordinate:", event.x)
    print("Window y-coordinate:", event.y)
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print("Canvas x-coordinate:", x)
    print("Canvas y-coordinate:", y)
    print("closest:", canvas.find_closest(x, y))

master = tk.Tk()

frame = tk.Frame(master, width=50, height=50, bd=5, bg="green", relief="groove")
frame.pack_propagate(0)
frame.pack()

button = tk.Button(frame)
button.pack(fill="none")

canvas = tk.Canvas(master, bd=5, width=50, height=50, bg="red", relief="ridge")
canvas.bind("<Button-1>", callback)
canvas.pack_propagate(0)
canvas.pack()

master.mainloop()

【问题讨论】:

    标签: tkinter tkinter-canvas


    【解决方案1】:

    如果您的画布能够滚动,您只需要进行转换。否则,窗口和画布坐标之间存在 1:1 映射。

    您可以在创建画布后的某个时间点通过将以下代码添加到您的示例中来看到这一点:

    canvas.configure(scrollregion=(0,0,1000,1000))
    canvas.yview_moveto(.5)
    canvas.xview_moveto(.5)
    

    还有另一种不常用的行为,即canvasxcanvasy 可以将坐标四舍五入为gridspacing 单位的大小。

    这是canvasx方法的canonical description

    给定画布 screenx 中的窗口 x 坐标,此命令返回显示在该位置的画布 x 坐标。如果指定了 gridspacing,则画布坐标将四舍五入到最接近的 gridspacing 单位倍数。

    您可以通过将对canvasxcanvasy 的调用更改为如下所示,这将返回始终是2 的倍数的坐标。

    x = canvas.canvasx(event.x, gridspacing=2)
    y = canvas.canvasy(event.y, gridspacing=2)
    

    【讨论】:

      猜你喜欢
      • 2011-12-10
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多