在可滚动的Tkinter画布

时间:2016-11-14 15:46:41

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

我试图这样做,以便当您右键单击时,该行突出显示为蓝色,然后您可以编辑或删除该条目。但是,由于添加滚动条,如果滚动页面,则选择将被偏移。

我试图建议找到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)

1 个答案:

答案 0 :(得分: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()

OR

我应该使用winfo_containing,这是一个很整洁的

相关问题