Advertisement
Uno-Dan

drag window

May 14th, 2020
1,623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1.  
  2. import tkinter as tk
  3. import tkinter.ttk as ttk
  4.  
  5.  
  6. class App(tk.Tk):
  7.     def __init__(self):
  8.         super().__init__()
  9.         self.rowconfigure(0, weight=1)
  10.         self.columnconfigure(1, weight=1)
  11.         self.title('Default Demo')
  12.         self.geometry('800x800')
  13.  
  14.  
  15. def main():
  16.     app = App()
  17.  
  18.     dw = tk.Toplevel()
  19.     dw.overrideredirect(True)
  20.     dw.wait_visibility(app)
  21.     dw.wm_attributes('-alpha', 0.2)
  22.     dw.wm_attributes("-topmost", True)
  23.     dw.config(bg='#00aaff')
  24.     dw.withdraw()
  25.  
  26.     def drag(event):
  27.         x, y = app.winfo_pointerxy()
  28.         width = event.x-app.anchor_x
  29.         height = event.y-app.anchor_y
  30.  
  31.         if width < 0:
  32.             coord_x = event.x+app.winfo_rootx()
  33.             width = app.anchor_x - event.x
  34.         else:
  35.             coord_x = app.anchor_x+app.winfo_rootx()
  36.  
  37.         if coord_x+width > app.winfo_rootx()+app.winfo_width():
  38.             width -= (coord_x+width)-(app.winfo_rootx()+app.winfo_width())
  39.         elif x < app.winfo_rootx():
  40.             width -= (app.winfo_rootx() - x)
  41.             coord_x = app.winfo_rootx()
  42.  
  43.         if height < 0:
  44.             coord_y = event.y+app.winfo_rooty()
  45.             height = app.anchor_y - event.y
  46.         else:
  47.             coord_y = app.anchor_y+app.winfo_rooty()
  48.  
  49.         if coord_y+height > app.winfo_rooty()+app.winfo_height():
  50.             height -= (coord_y+height)-(app.winfo_rooty()+app.winfo_height())
  51.         elif y < app.winfo_rooty():
  52.             height -= (app.winfo_rooty() - y)
  53.             coord_y = app.winfo_rooty()
  54.  
  55.         dw.geometry(f'{width}x{height}+{coord_x}+{coord_y}')
  56.  
  57.     def button_press(event):
  58.         dw.deiconify()
  59.         app.anchor_x, app.anchor_y = event.x, event.y
  60.         app.bind('<Motion>', drag)
  61.  
  62.     def button_release(event):
  63.         dw.withdraw()
  64.         dw.geometry('0x0+0+0')
  65.         app.unbind('<Motion>')
  66.  
  67.     app.bind('<Button-1>', button_press)
  68.     app.bind('<ButtonRelease-1>', button_release)
  69.  
  70.     app.mainloop()
  71.  
  72.  
  73. if __name__ == '__main__':
  74.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement