Search code examples
pythonpython-3.xtkintertclttk

Tkinter, ignore certain lines from a tcl file?


Basically, I just want to remove the mouse scrollwheel binding for scrolling in ttk.Treeview widget. And I found that a specific line in the file found in

Python.framework/Versions/3.9/lib/tk8.6/ttk/treeview.tcl 

is responsible for it, that if removed, disables the mouse scrollwheel for scrolling the view:

ttk::copyBindings TtkScrollable Treeview 

However, I don't want to affect the built-in files. My only solution was to create py2app bundle and delete the same line from the treeview.tcl inside the bundle. But is there a direct way to do this inside a script.py file without affecting the tcl file?


Solution

  • You don't have to modify the original code. Tkinter's event handling mechanism is very robust. It's easy to prevent the default bindings from running, bind binding a function that returns the string "break". Returning "break" will prevent any other handlers in the widget's binding tags from being invoked.

    Here's a short contrived example:

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    
    tree = ttk.Treeview(root)
    tree.pack(side="top", fill="both", expand=True)
    for i in range(20):
        tree.insert("", "end", text=f"Item #{i+1}")
    
    tree.bind("<MouseWheel>", lambda event: "break")
    root.mainloop()
    

    Note if you're on an x11 based system you might have to disable the bindings for <Button-4> and <Button-5> instead of <MouseWheel>.