如何在Tkinter窗口中设置鼠标位置 [英] How can I set the mouse position in a tkinter window

查看:343
本文介绍了如何在Tkinter窗口中设置鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3d渲染程序,该程序根据鼠标在屏幕上的位置旋转观察者周围的世界.这条线定义了地球旋转的弧度量

I have a 3d rendering program that rotates the world around an observer based on the position the mouse is on the screen. The amount in radians that the world is rotated is defined by this line

    glob.worldx=-(w.winfo_pointerxy()[0]-xy[0])/250

其中xy [0]是屏幕中心的x坐标

Where xy[0] is the x coordinate of the center of the screen

这意味着观察者视野的旋转量受到鼠标可以移动的距离的限制.如果我能使鼠标回到屏幕中心,则可以解决此问题.有什么想法吗?

This means that the amount that the observers field of view can be rotated is limited by the distance the mouse can go. If I could get the mouse to come back to the center of the screen I could solve this problem. Any ideas?

推荐答案

好消息是,有一种方法可以实现.

The good news is that there is a way to do it.

中间的消息是,它没有得到很好的记录.

The intermediate news is that it's not well documented.

坏消息是它仅在某些平台上有效.

The bad news is that it only works on some platforms.

另一个中间消息是,您至少可以在某些平台上走出Tk.

The other intermediate news is that you can step outside of Tk on at least some platforms.

在Tcl/Tk中执行此操作的方法是使用-warp 1生成一个<Motion>事件.有关此文档的文档很少,并且散布在几个不同的页面上(从开始bind ),但在此处中进行了详细说明.基本上就是这样:

The way to do this in Tcl/Tk is by generating a <Motion> event with -warp 1. The documentation on this is sparse, and scattered around a few different pages (start at bind), but the details are described here. Basically, it's just this:

event generate . <Motion> -warp 1 -x 50 -y 50

那么,您如何从Tkinter做到这一点?

So, how do you do this from Tkinter?

好吧,event_generate在任何地方都没有记录,<Motion>事件或warp参数都没有……但是很容易弄清楚是否知道Tk如何映射到Tkinter:

Well, event_generate isn't documented anywhere, and neither is the <Motion> event, or the warp parameter… but it's pretty simple to figure out if you know how Tk maps to Tkinter:

window.event_generate('<Motion>', warp=True, x=50, y=50)

这确实会生成一个事件,如通过绑定<Motion>可以看到的.这是一个简单的测试程序:

And this does indeed generate an event, as you can see by binding <Motion>. Here's a simple test program:

from tkinter import *

root = Tk()

def key(event):
    root.event_generate('<Motion>', warp=True, x=50, y=50)

def motion(event):
    print('motion {}, {}'.format(event.x, event.y))

root.bind('<Key>', key)
root.bind('<Motion>', motion)
root.mainloop()

运行它,单击窗口以确保它具有焦点,将光标四处移动,您会看到它打印出如下内容:

Run it, click the window to make sure it has focus, move the cursor around, and you'll see it print out something like this:

motion 65, 69
motion 65, 70
motion 65, 71

然后按下一个键,它将打印出以下内容:

Then hit a key, and it'll print out this:

motion 50, 50

这很不错……除了它实际上可能无法移动光标之外,在这种情况下,所有这一切都使Tk误以为光标已经移动了.

Which is great… except that it may not actually be able to move your cursor, in which case all this does is trick Tk into thinking the cursor moved.

通过浏览各种论坛,看起来像:

From skimming various forums, it looks like:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆