You dont ever have to use classes. You could just make
self.root a global variable
root and just a function called OnDoubleClick() and have the same effect.
As your program grows larger and larger, you kinda realize that the no class method isnt all that great and that modularizing the code into classes and modules makes more sense. It isnt all that required in the example you linked to...but after you use classes its hard to not use them. However, adding content to their example is much easier. All you need to do is add a method to the class or create a new class and put the object in that class, etc. It also a lot more easier to read.
As for their use here...the dunder init method (__init__) is all the content that is prep work at the time of
App()
where the single method is for double click events. The
if __name__ == "__main__":
is a way to only run code if that is executed directly...albeit not imported to another script as a module it will not run. Its a way to run a module in a test mode per se in a specific event.
I would personally prefer it like this where you send the class root...as other classes might need the root window as well. As well as split up and better document methods.
import tkinter as tk
import tkinter.ttk as ttk
class App:
def __init__(self, window):
self.setup_tree()
self.tree.bind("<Double-1>", self.OnDoubleClick)
def setup_tree(self):
'''setup Treeview and insert values'''
self.tree = ttk.Treeview()
self.tree.pack()
for i in range(10):
self.tree.insert("", "end", text="Item %s" % i)
def OnDoubleClick(self, event):
'''handle double click event'''
item = self.tree.identify('item',event.x,event.y)
print("you clicked on", self.tree.item(item,"text"))
root = tk.Tk()
App(root)
root.mainloop()