I'm currently trying to move a button by using drag and drop with tkinter. The problem is that when I'm trying to move my button, it's working but I can't move it outside his parent: I have a LabelFrame which contains several LabelFrame with buttons. I'm trying to drag and drop a button from a LabelFrame to the other one but when the button is going outside of his parent, it "disappears". I'm using the method "place" of the widget to move it during my drag.
I'm not sure if my problem is really understandable. I'll put some codes if it isn't to explain it better.Answer1:
Widgets exist in a hierarchy, and every widget will be visually clipped by its parent. Since you want a widget to appear in different frames at different times, it simply cannot be a child of either frame. Instead, make it a child of the parent of the frames. You can then use
grid) to put the widget in either frame by using the
Here's an example. It doesn't use drag and drop in order to keep the code compact, but it illustrates the principle. Click on the button to move it from one frame to the other.
import tkinter as tk class Example: def __init__(self): self.root = tk.Tk() self.lf1 = tk.LabelFrame(self.root, text="Choose me!", width=200, height=200) self.lf2 = tk.LabelFrame(self.root, text="No! Choose me!", width=200, height=200) self.lf1.pack(side="left", fill="both", expand=True) self.lf2.pack(side="right", fill="both", expand=True) self.button = tk.Button(self.root, text="Click me", command=self.on_click) self.button.place(in_=self.lf1, x=20, y=20) def start(self): self.root.mainloop() def on_click(self): current_frame = self.button.place_info().get("in") new_frame = self.lf1 if current_frame == self.lf2 else self.lf2 self.button.place(in_=new_frame, x=20, y=20) Example().start()