英文:
Tkinter get_mouse
问题
当我的鼠标移出画布时,我仍然在左上角看到一个圆圈,并且在终端中打印出了-1 -1。为什么?
mouse_x = canvas.get_mouse_x()
mouse_y = canvas.get_mouse_y()
canvas.create_oval(mouse_x, mouse_y, mouse_x + SIZE, mouse_y + SIZE)
print(mouse_x, mouse_y)
我知道如何改进我的代码。我只是觉得在这种情况下为什么仍然会有输出。
英文:
When my mouse is outside the canvas, I still get a circle located at the top left corner. And I can see printed -1 -1 in the terminal. Why?
mouse_x = canvas.get_mouse_x()
mouse_y = canvas.get_mouse_y()
canvas.create_oval(mouse_x, mouse_y, mouse_x + SIZE, mouse_y + SIZE)
print(mouse_x, mouse_y)
I know how to improve my code. It's just interesting to me why I still get something in this case.
答案1
得分: 2
当鼠标位于画布外时,canvas.get_mouse_x()
和 canvas.get_mouse_y()
将返回值 -1
。这是因为画布坐标从左上角 (0, 0) 开始,当鼠标在画布外时,没有有意义的坐标可返回。
在你的代码中,你使用返回值 -1
作为创建椭圆的 x 和 y 坐标,使用 canvas.create_oval()
。这将在画布的左上角创建一个椭圆,宽度和高度为 SIZE。
print(mouse_x, mouse_y)
语句将在终端打印 -1 -1
,表示鼠标当前位于画布外部。
英文:
When the mouse is outside the canvas, canvas.get_mouse_x()
and canvas.get_mouse_y()
will return the value -1
. This is because the canvas coordinates start at (0, 0) in the top left corner, and when the mouse is outside the canvas, there is no meaningful coordinate to return.
In your code, you are using the returned value of -1
as the x and y coordinates for creating an oval using canvas.create_oval()
. This will create an oval at the top left corner of the canvas, with a width and height of SIZE.
The print(mouse_x, mouse_y)
statement will print -1 -1
to the terminal, indicating that the mouse is currently outside the canvas.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论