How to get the widget's current x and y coordinates?

戏子无情 提交于 2020-12-23 10:57:27

问题


I'm currently writing a game project as for the game "4 in a row". To make the animation where the picture widget disk falls in the column, I've been thinking about creating a while loop for as in:

while widgetx != __ and widgety != __

where at the blank parts there will be the values I'll need to get.

My question is if there's a function that returns the current x and y value for a widget.


回答1:


winfo_rootx() and winfo_rooty() return the coordinates relative to the screen's upper left corner. winfo_x and winfo_y return the coordinates of a window relative to its parent.




回答2:


You can try winfo_rootx() and winfo_rooty().

From effbot.com:

winfo_rootx()

Get the pixel coordinate for the widget’s left edge, relative to the screen’s upper left corner.

Returns: The root coordinate.

winfo_rooty()

Get the pixel coordinates for the widget’s upper edge, relative to the screen’s upper left corner.

Returns: The root coordinate.

An example from nullege.com:

# get self position & height
lv_x = self.winfo_rootx()
lv_y = self.winfo_rooty()



回答3:


Yes there is, it is a method of a widget named coords,

coords(tagOrId, x0, y0, x1, y1, ..., xn, yn) Queries or modifies the coordinates that define an item. If no coordinates are specified, this method returns a tuple whose elements are the coordinates of the item named by tagOrId. If coordinates are specified, then they replace the current coordinates for the named item. If tagOrIdrefers to multiple items, then the first one in the display list is used - From "Python and Tkinter Programming" by John E. Grayson

Example:

root = Tk()
calibCanvas = Canvas(root, width=800,height=800,bg='WHITE')     
canvasRect = calibCanvas.create_rectangle(400,400,410,410, outline='BLUE')  
print calibCanvas.coords(canvasRect)


来源:https://stackoverflow.com/questions/30257574/how-to-get-the-widgets-current-x-and-y-coordinates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!