CustomTkinter select correct tab on hover when doing drag and drop

104 Views Asked by At

My CTK code enters the required tab when hovering the mouse as desired and it allows me to drag and drop with DND if the correct tab is already selected, but is there a method to combine the two actions? All too often I forget to select the correct tab before I drag the file and then I end up dropping it in some inappropriate place (on the desktop, in another folder, ...) before I can click the correct tab.

With my code below I would like to automatically select Input Tab if I am on Wrong Tab and in DND mode.

import customtkinter as ctk
from tkinterdnd2 import TkinterDnD, DND_ALL
from tkinter import StringVar

class TabView(ctk.CTkTabview, TkinterDnD.DnDWrapper):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.TkdndVersion = TkinterDnD._require(self)
        global path_string

        # Create tabs.
        self.add('Input Tab')
        self.add('Wrong Tab')

        # Input file drag and drop.
        path_string = StringVar(value='Drop a file here')
        self.PathLabel = ctk.CTkLabel(master=self.tab('Input Tab'), text='Input File', anchor='w')
        self.PathLabel.grid(row=0, column=0, padx=10, pady=10, sticky='ew')
        self.PathEntry = ctk.CTkEntry(master=self.tab('Input Tab'), textvariable=path_string)
        self.PathEntry.grid(row=0, column=1, columnspan=3, padx=10, pady=10, sticky='ew')
        self.PathEntry.drop_target_register(DND_ALL)
        self.PathEntry.dnd_bind('<<Drop>>', self.fn_get_path)

    def fn_get_path(self, event):
        path_string.set(value=event.data.strip('{}'))
        print(self.PathEntry.get())

class App(ctk.CTk):
    def fn_input_hover(self, event):
        self.tab_view._segmented_button._buttons_dict['Input Tab'].invoke()

    def fn_input_leave(self, event):
        pass

    def __init__(self):
        super().__init__()

        self.tab_view = TabView(master=self)
        self.tab_view.grid(row=0, column=0, padx=20, pady=20)

        # Enter input tab on hover.
        self.tab_view._segmented_button._buttons_dict['Input Tab'].bind('<Enter>', self.fn_input_hover, add='+')
        self.tab_view._segmented_button._buttons_dict['Input Tab'].bind('<Leave>', self.fn_input_leave, add='+')

app = App()
app.mainloop()
0

There are 0 best solutions below