python turtle 获取鼠标坐标_如何使用tkinter和turtle获得鼠标位置?

You've got an issue working against you that isn't of your own making. The general rule is when in a turtle canvas, use turtle methods. But turtle doesn't have an inherent 'Motion' event type, so you were trying to use the raw Canvas one as a substitute. Thus the conflict.

您自己遇到的一个问题是,当您处于快速移动的事件处理程序内部时,首先需要禁用事件处理程序,然后在退出时重新启用。否则,事件会重叠并且发生坏事。 (无意的递归和其他问题。)

我已经按照您的意图重写了下面的程序,使其可以正常工作。解决方法是添加缺少的turtle方法,以便我们可以停留在turtle域内:

import tkinter as tk

from turtle import RawTurtle, TurtleScreen

from functools import partial

def onscreenmove(self, fun, add=None): # method missing from turtle.py

if fun is None:

self.cv.unbind('')

else:

def eventfun(event):

fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale)

self.cv.bind('', eventfun, add)<

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 您可以使用 `turtle.onscreenclick()` 方法来获取鼠标点击的位置。以下是一个简单的例子: ```python import turtle def get_mouse_click_coor(x, y): print(x, y) turtle.onscreenclick(get_mouse_click_coor) turtle.mainloop() ``` 在这个例子,当鼠标点击时,`get_mouse_click_coor()` 函数会被调用,并传递鼠标点击的 x 和 y 坐标作为参数。该函数打印出这些坐标。 注意:`turtle.mainloop()` 方法用于保持窗口打开。如果省略此行,则窗口将立即关闭。 ### 回答2: 在Python,我们可以使用`turtle`模块来创建绘图程序。然而,`turtle`模块本身并不提供鼠标事件的处理功能。但我们可以借助其他模块来实现鼠标位置的功能。 一种常用的方法是使用`tkinter`模块。首先,我们需要导入`turtle`和`tkinter`模块: ```python import turtle import tkinter as tk ``` 然后,我们可以创建一个继承自`turtle.TurtleScreen`类的自定义类,并重写`onclick`方法来处理鼠标点击事件: ```python class MyTurtleScreen(turtle.TurtleScreen): def onclick(self, x, y): print("鼠标点击位置:", x, y) # 在这里处理鼠标点击的逻辑 ``` 接下来,我们需要创建一个`tkinter`的主窗口,并将它绑定到`turtle`画布上: ```python root = tk.Tk() canvas = turtle.ScrolledCanvas(root) canvas.pack() ``` 然后,我们创建一个`MyTurtleScreen`对象,并将它绑定到刚刚创建的画布上: ```python screen = MyTurtleScreen(canvas) turtle.RawTurtle(screen) ``` 最后,我们启动`tkinter`的主循环来监听鼠标事件: ```python tk.mainloop() ``` 当鼠标点击画布时,`onclick`方法将会被调用,并且会输出鼠标点击位置坐标。你可以在`onclick`方法添加任何你想执行的逻辑。注意,鼠标点击的位置是相对于画布左上角的坐标。 希望以上解答对你有所帮助! ### 回答3: 在Python turtle,可以通过使用`onscreenclick()`函数绑定鼠标点击事件,并使用`xcor()`和`ycor()`函数获取鼠标点击位置坐标。具体步骤如下: 首先,导入`turtle`库。可以使用以下命令实现: ```python import turtle ``` 然后,创建一个`turtle`对象,并设置画布尺寸: ```python wn = turtle.Screen() wn.setup(width=500, height=500) ``` 接下来,定义一个函数来处理鼠标点击事件,并在其获取鼠标点击位置坐标: ```python def handleClick(x, y): print("鼠标点击位置:", x, y) ``` 然后,使用`turtle`对象的`onscreenclick()`函数绑定上述函数到鼠标点击事件上: ```python wn.onscreenclick(handleClick) ``` 最后,调用`turtle`库的`mainloop()`函数来监听并响应鼠标点击事件: ```python turtle.mainloop() ``` 当你运行上述代码后,每当你在画布上点击鼠标,终端将会打印出鼠标点击位置的x和y坐标。 总结起来,以上步骤实现了使用Python turtle获取鼠标点击位置的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值