Tkinter custom drawing

James Stroud jstroud at mbi.ucla.edu
Fri Jun 8 18:51:13 EDT 2007


Xavier Bérard wrote:
>>>Now, the problem, is that I have already plenty of widgets on my
>>>screen. I just want to draw over them, which is a bit difficult in my
>>>comprehension of things.
>>
>>What are you trying to achieve by "drawing over" widgets?
> 
> 
> 
> Want I want to do is a sort of GUI builder for Tkinter. I already
> finished a rough version, but for now I'm making a lighter version of
> this project. So, my intent, is to create a widget under the widget.
> While dragging the mouse, I want to see this rectangle that defines
> the boundaries of the new widget I'm creating.
> 
> Sorry for being unclear.
> 

You may want to look into the place() method. The python mega widgets 
(PMW) has a PanedWidget that implements this smoothly. You may want to 
emulate that approach:


#! /usr/bin/env python

from Tkinter import *

def button_pressed(e):
   moved = e.widget
   moved.move_pending = True
   moved['cursor'] = 'hand1'
   moved.press_x = e.x
   moved.press_y = e.y

def button_moved(e):
   moved = e.widget
   if moved.move_pending:
     moved.after_idle(lambda e=e: _button_moved(e))
     moved.move_pending = False

def _button_moved(e):
   moved = e.widget
   delta_x = e.x - moved.press_x
   delta_y = e.y - moved.press_y
   size, wx, wy = moved.winfo_geometry().split('+')
   new_x = int(wx) + delta_x
   new_y = int(wy) + delta_y
   moved.place(x=new_x, y=new_y)
   moved.update_idletasks()
   moved.move_pending = True

def button_up(e):
   e.widget['cursor'] = ''

def register(widget):
   widget.bind('<ButtonPress-3>', button_pressed)
   widget.bind('<B3-Motion>', button_moved)
   widget.bind('<Any-ButtonRelease-3>', button_up)
   widget.update_idletasks()

def test():
   tk = Tk()

   b = Button(tk, text='Button')
   b.pack()
   c = Button(tk, text='Another Button')
   c.pack()
   x = Label(tk, text='Drag Me', relief=RIDGE, border=1)
   register(x)
   x.pack()

   tk.geometry('200x200')
   tk.mainloop()

if __name__ == "__main__":
   test()


James



More information about the Python-list mailing list