【问题标题】:Finding coordinates on a scrollable Tkinter canvas在可滚动的 Tkinter 画布上查找坐标
【发布时间】:2016-11-14 15:46:40
【问题描述】:

我正在尝试这样做,以便当您右键单击时,该行以蓝色突出显示,然后您可以编辑或删除该条目。但是,由于添加了滚动条,如果页面被滚动,那么选择就会发生偏移。

我试图建议找到 canvasx 和 canvasy,然后使用 find_closest(0,但是当我这样做时,无论如何它总是返回 (1,)。

Canvasx 和 canvasy 对于每个标签来说似乎都是本地的,而不是画布本身

from tkinter import *

def RightClick(event):
    #Find widgets on the row that was right clicked
    print(canvas.canvasy(event.y))
    for widget in frame.winfo_children():
        mouseClickY = event.y_root - root.winfo_y() - widget.winfo_height()
        widgetTopY = widget.winfo_y()
        widgetBottomY = widget.winfo_y() + widget.winfo_height()

        if (widget.winfo_class() == "Label") and (mouseClickY > widgetTopY) and (mouseClickY < widgetBottomY):
            #Highlight that row
            if widget.cget("bg") != "#338fff":
                widget.config(bg = "#338fff", fg="#FFFFFF")

        #Deselect all rows        
        elif widget.winfo_class() == "Label":
            widget.config(bg = "#FFFFFF", fg="#000000")

def onFrameConfigure(event):
    canvas.configure(scrollregion=canvas.bbox("all"))

root = Tk()
root.bind("<Button-3>", RightClick)

canvas = Canvas(root, width = 1080, height=500)
frame = Frame(canvas)  
scrollbar = Scrollbar(root, command=canvas.yview)
canvas.config(yscrollcommand=scrollbar.set) 

canvas.grid(row=1,column=0,columnspan=5)
canvas.create_window((0,0), window=frame, anchor="nw",tags="frame")
scrollbar.grid(column=5,row=1,sticky="NS")

frame.bind("<Configure>", onFrameConfigure)

for countY in range(40):
    for countX in range(6):
        l = Label(frame, text=countX, width = 25, height = 1, bg="#FFFFFF")
        l.grid(column=countX,row=countY+1)

【问题讨论】:

  • 那是需要更多的代码,加上你的缩进被破坏了。请阅读How to create a Minimal, Complete and Verifiable Example
  • 抱歉,我会解决的。通常当我在这里发布时,我被告知要发布更多代码,所以我这样做了
  • 我们只需要足够的代码来重现问题,仅此而已。
  • 我更新了它,我认为现在应该会更好
  • 您是否知道winfo_containing 方法会告诉您在给定坐标下的小部件是什么?您可以给它事件的根坐标以获取光标下的小部件。

标签: python-3.x tkinter tkinter-canvas


【解决方案1】:

解决了,结果

mouseClickY = event.y_root - root.winfo_y() - widget.winfo_height()
widgetTopY = widget.winfo_y()
widgetBottomY = widget.winfo_y() + widget.winfo_height()

应该是

mouseClickY = event.y_root - root.winfo_y()
widgetTopY = widget.winfo_rooty()
widgetBottomY = widget.winfo_rooty() + widget.winfo_height()

我应该使用winfo_containing,它更整洁

【讨论】:

    猜你喜欢
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2019-02-09
    相关资源
    最近更新 更多