2016-11-14 143 views
3

我試圖讓這個當你右鍵點擊,該行突出的藍色,然後你可以編輯或刪除該條目。但是,由於添加了滾動條,如果頁面滾動,則選擇將被偏移。尋找座標上滾動的帆布的Tkinter

我試圖0找到canvasx和canvasy,然後使用find_closest的建議的事情(,但是當我這樣做,它總是返回(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

也就是說waaaaay更多的代碼是必要的,再加上你的縮進被打破。請參閱[如何創建一個最小的,完整的和可驗證的示例](http://www.stackoverflow.com/help/mcve) –

+0

對不起,我會解決這個問題。通常當我在這裏發帖時,我被告知要發佈更多代碼,所以我做了 – Mrchooch

+1

我們只需要足夠的代碼來重現問題,沒有什麼更多。 –

回答

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,這是一個很大整潔