Home > Blockchain >  tkinter Treeview: pass event and variable to another function in another module
tkinter Treeview: pass event and variable to another function in another module

Time:10-04

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.

CodePudding user response:

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))
  • Related