Skip to content Skip to sidebar Skip to footer

How To Move Button Outside Of His Parent With Tkinter?

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 paren

Solution 1:

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 place (or pack or grid) to put the widget in either frame by using the in_ parameter.

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

classExample:
    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)

    defstart(self):
        self.root.mainloop()

    defon_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()

Post a Comment for "How To Move Button Outside Of His Parent With Tkinter?"