如何使用 tkinter 将按钮移到 parent 之外?

How to move button outside of his parent with tkinter?

我目前正在尝试使用 tkinter 拖放来移动按钮。 问题是,当我尝试移动我的按钮时,它可以正常工作,但我无法将它移到他的 parent 之外: 我有一个 LabelFrame,其中包含几个带按钮的 LabelFrame。我试图将一个按钮从 LabelFrame 拖放到另一个按钮,但是当按钮超出他的 parent 时,它 "disappears"。 我正在使用小部件的方法 "place" 在拖动过程中移动它。

我不确定我的问题是否真的可以理解。如果不是为了更好地解释它,我会放一些代码。

小部件存在于层次结构中,每个小部件都将被其父级在视觉上裁剪。由于您希望小部件在不同时间出现在不同的框架中,因此它不能是任一框架的子级。相反,使它成为框架父级的子级。然后,您可以使用 place(或 packgrid)通过使用 in_ 参数将小部件放在任一框架中。

举个例子。它没有使用拖放来保持代码紧凑,但它说明了原理。单击按钮将其从一帧移动到另一帧。

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