Tkinter Python 3-移动无边界窗口

时间:2018-12-05 22:21:04

标签: python python-3.x windows tkinter



这篇文章实际上与this存在相同的问题,但是代替了Python 3中的Python 2,并且如果您可以精确地说出哪个框架也将是一个很好的事实。拖动实际上会按照期望的方式移动(如示例代码中的“ top_Frame”)。

示例代码:

from tkinter import *

def main():
    root = Tk()
    root.geometry("200x200")
    root.resizable(0, 0)
    root.overrideredirect(1)

    back = Frame(root, bg="grey")
    back.pack_propagate(0)
    back.pack(fill=BOTH, expand=1)

    top_Frame = Frame(back, bg="#505050")
    top_Frame.place(x=0, y=0, anchor="nw", width=200, height=20)
    '''Would Be great if it could be specified to only be moved
    when dragging with the Frame above.'''

    Ext_but = Button(top_Frame, text="X", bg="#FF6666", fg="white", command=lambda: exit())
    Ext_but.place(x=170, y=0, anchor="nw", width=30, height=20)

    root.mainloop()

main()

1 个答案:

答案 0 :(得分:0)

使用类包装所有功能的完整示例:

from tkinter import *

class Grip:
    ''' Makes a window dragable. '''
    def __init__ (self, parent, disable=None, releasecmd=None) :
        self.parent = parent
        self.root = parent.winfo_toplevel()

        self.disable = disable
        if type(disable) == 'str':
            self.disable = disable.lower()

        self.releaseCMD = releasecmd

        self.parent.bind('<Button-1>', self.relative_position)
        self.parent.bind('<ButtonRelease-1>', self.drag_unbind)

    def relative_position (self, event) :
        cx, cy = self.parent.winfo_pointerxy()
        geo = self.root.geometry().split("+")
        self.oriX, self.oriY = int(geo[1]), int(geo[2])
        self.relX = cx - self.oriX
        self.relY = cy - self.oriY

        self.parent.bind('<Motion>', self.drag_wid)

    def drag_wid (self, event) :
        cx, cy = self.parent.winfo_pointerxy()
        d = self.disable
        x = cx - self.relX
        y = cy - self.relY
        if d == 'x' :
            x = self.oriX
        elif d == 'y' :
            y = self.oriY
        self.root.geometry('+%i+%i' % (x, y))

    def drag_unbind (self, event) :
        self.parent.unbind('<Motion>')
        if self.releaseCMD != None :
            self.releaseCMD()

def main():
    root = Tk()
    root.geometry("200x200")
    root.resizable(0, 0)
    root.overrideredirect(1)

    back = Frame(root, bg="grey")
    back.pack_propagate(0)
    back.pack(fill=BOTH, expand=1)

    top_Frame = Frame(back, bg="#505050")
    top_Frame.place(x=0, y=0, anchor="nw", width=200, height=20)
    '''Would Be great if it could be specified to only be moved
    when dragging with the Frame above.'''
    grip = Grip(top_Frame)

    Ext_but = Button(top_Frame, text="X", bg="#FF6666", fg="white", command=lambda: exit())
    Ext_but.place(x=170, y=0, anchor="nw", width=30, height=20)

    root.mainloop()

main()

请注意,此类中有一些额外的位(我从以前做过的操作中复制了它),因为它可用于限制可以拖动的方向(disable标志)并在拖动停止时触发回调