1

I have problem when passing Tk treeview event to another module. I will demonstrate problem on a code from already answered question from KokoEfraim here.

I have main module with the same code except for function selectItem, which I put into Functions.py:

Main.py:

from tkinter import *
from tkinter import ttk
import Main_functions as Main_functions

root = Tk()
tree = ttk.Treeview(root, columns=("size", "modified"))
tree["columns"] = ("date", "time", "loc")

tree.column("date", width=65)
tree.column("time", width=40)
tree.column("loc", width=100)

tree.heading("date", text="Date")
tree.heading("time", text="Time")
tree.heading("loc", text="Loc")
tree.bind('<ButtonRelease-1>', Main_functions.selectItem)

tree.insert("","end",text = "Name",values = ("Date","Time","Loc"))

tree.grid()
root.mainloop()

Main_functions:

from tkinter import *

def selectItem(a):
    curItem = tree.focus()
    print(tree.item(curItem))

With this comes my problem, because I receive error NameError: name 'tree' is not defined, because unlike in the original, I put the selectItem function into another .py and therefore the tree is not recognized there.

Which brings me to a question, am I able to pass into selectItem a variable? Because putting more variables into the function raises error with too many passed variables, as event is not passed in a standard way.

I have tried another solution such as a.widget.focus, but non are working.

1
  • 1
    a.widget.focus() should work in your case. But you need to change tree.item(curItem) to a.widget.item(curItem) as well. Commented Oct 3, 2022 at 15:48

1 Answer 1

1

In this specific case, selectItem will be passed an object representing the event. One of the attributes of that object is a reference to the widget that received the event. So, you can write your selectItem method to use that information:

def selectItem(event):
    tree = event.widget
    curItem = tree.focus()
    print(tree.item(curItem))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.