How to move button outside of his parent with tkinter?

孤人 提交于 2019-12-23 19:26:40

问题


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.


回答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

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


来源:https://stackoverflow.com/questions/47290791/how-to-move-button-outside-of-his-parent-with-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!