How to use grid_location (Tkinter)

Rick Pasotto rickp at telocity.com
Thu Aug 24 15:58:23 EDT 2000


On Thu, 24 Aug 2000 14:17:40 GMT in comp.lang.python, Carles Sadurní
Anguita wrote:
> Hello,
> 
> I would like to divide a window in a 3x3 grid of labels and then know
> in which cell did the user click (for instance (2,1)).
> 
> I've read Fredrik Lundh's Tkinter Introduction, Tk man pages, chapter
> 5 from John Grayson's book, some exemples and so, but I can't figure
> out how to use grid_location (if it's the method I should use).
> 
> Currently my code is
> 
> ------------------------------Begin code---------------------------
> 
> #!/usr/bin/python
> 
> from Tkinter import *
> import sys
> 
> class application:
> 
> 	def click(self, event):
> 		print "Clicked ", event.x, event.y
> 
> 	def __init__(self, master=None):
> 		self.master = master
> 
> 		for r in range(3):
> 			for c in range(3):
> 				lbl = Label(master, text = 1000 + r + c)
> 				lbl.grid(row = r, column = c, sticky = NSEW)
> 				
> root = Tk()
> root.title('Parrilla horària')
> g = application(root)
> root.bind("<Button-1>", g.click)
> root.mainloop()
> 
> ----------------------------End code-----------------------------
> 
> Can anybody show me the correct way?

I'm just learning python and Tkinter myself and this was a challenging
question.

There are two non-obvious points that you are missing.

First, grid_location() is a *widget* method that gives information about
widgets that it contains. But the master window is not a widget, so you
need to put the labels inside a Frame that you have called grid() on.

Second, the x,y values it is looking for are relative to the upper left
corner of the containing widget. So what you need to do is:

x = event.x_root - frame.winfo_rootx
y = event.y_root - frame.winfo_rooty
(col,row) = frame.grid_location(x,y)


-- 
"I will be as harsh as truth and as uncompromising as justice.
On this subject I do not wish to think, or speak, or write, with
moderation.  No!  No!  Tell a man whose house is on fire to give
a moderate alarm; tell him to moderately rescue his wife from the
hands of the ravisher; tell the mother to gradually extricate her
babe from the fire into which it has fallen; but urge me not to
use moderation."
		-- William Lloyd Garrison, _The Liberator_ (1831)
		   Rick Pasotto email: rickp at vnet.net



More information about the Python-list mailing list