繁体   English   中英

Tkinter python 3 - 移动无边框窗口

[英]Tkinter python 3 - Moving a borderless window



这篇文章实际上与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()

一个完整的例子,它使用一个类来包装所有功能:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM