本文介绍了按钮具有根据“网格位置”的自己的坐标系统。方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Tkinter中的 Grid Geometry Manager 中的 grid_location
方法,但似乎我在做有问题。
以下是我的代码:
from tkinter import *
root = Tk()
b = Button(root,text =00)
b.grid(row = 0,column = 0)
b2 = Button(root,text =11)
b2.grid(row = 1,column = 1)
b3 = Button(root,text =22)
b3.grid(row = 2,column = 2)
b4 = Button(root,text =33)
b4.grid(row = 3,column = 3)
b5 =按钮(root,text =44)
b5.grid(row = 4,column = 4)
def mouse(event):
print(event.x ,event.y)
print(root.grid_location(event.x,event.y))
root.bind(< Button-1>,mouse)
root.mainloop()
当我点击按钮外部时,当我点击任何按钮的内部时,似乎每个按钮都有自己的坐标系。因此,尽管代码中的每个按钮都位于(0,0)单元格中,但它们都位于规则网格中。 解决方案
p>你是正确的,每个按钮有它自己的坐标系。但更准确的说, event.x
和 event.y
值是相对于与事件关联的小部件而言的比窗口小部件的父窗口或根窗口。
如果你确实需要widget的行和列,你可以使用 grid_info
来获取行和与该事件关联的小部件的列。例如:
def mouse(event):
grid_info = event.widget.grid_info()
print(row:,grid_info [row],column:,grid_info [column])
I'm trying to use the grid_location
method, from the Grid Geometry Manager, in Tkinter, but it seems that I'm doing something wrong.
Here's my code:
from tkinter import *
root = Tk()
b=Button(root, text="00")
b.grid(row=0, column=0)
b2=Button(root, text="11")
b2.grid(row=1, column=1)
b3=Button(root, text="22")
b3.grid(row=2, column=2)
b4=Button(root, text="33")
b4.grid(row=3, column=3)
b5=Button(root, text="44")
b5.grid(row=4, column=4)
def mouse(event):
print(event.x, event.y)
print(root.grid_location(event.x, event.y))
root.bind("<Button-1>", mouse)
root.mainloop()
When I click outside the Buttons, it works, but when I click inside of any Button, it seems that each button has its own coordinate system. So, each button is on the (0, 0) cell, despite that in the code, they are on a regular grid.
解决方案
You are correct that each button "has it's own coordinate system". More accurately, though, the event.x
and event.y
values are relative to the widget associated with the event rather than the widget's parent or the root window.
If you really do need the row and column that the widget is in you can use grid_info
to get the row and column of the widget associated with the event. For example:
def mouse(event):
grid_info = event.widget.grid_info()
print("row:", grid_info["row"], "column:", grid_info["column"])
这篇关于按钮具有根据“网格位置”的自己的坐标系统。方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!