tk 的simpledialog使用时如何在当前鼠标位置弹出?
时间: 2024-03-14 18:42:59 浏览: 161
在 Tkinter 中,可以使用 `tkinter.simpledialog` 模块中的 `SimpleDialog` 类来实现简单对话框的功能,但是该类并没有提供直接在当前鼠标位置弹出对话框的方法。
不过,我们可以通过以下步骤来实现在当前鼠标位置弹出 `SimpleDialog`:
1. 获取当前鼠标位置。可以使用 `tkinter` 的 `winfo_pointerxy` 方法获取当前鼠标位置的 X 和 Y 坐标。
2. 计算对话框的位置。可以根据当前鼠标位置、对话框的大小以及屏幕的大小来计算对话框的位置。
3. 创建 `SimpleDialog` 对象,并设置其位置。可以使用 `SimpleDialog` 的 `geometry` 方法设置对话框的位置,具体来说,可以将计算出的对话框位置作为参数传递给 `geometry` 方法。
下面是一个示例代码,可以在当前鼠标位置弹出一个大小为 300x200 的 `SimpleDialog`:
```python
import tkinter as tk
import tkinter.simpledialog as sd
class MyDialog(sd.SimpleDialog):
def __init__(self, parent):
super().__init__(parent, title="My Dialog", width=300, height=200)
root = tk.Tk()
# 获取当前鼠标位置
x, y = root.winfo_pointerxy()
# 计算对话框位置
width, height = 300, 200
screen_width, screen_height = root.winfo_screenwidth(), root.winfo_screenheight()
x = max(0, min(x, screen_width - width))
y = max(0, min(y, screen_height - height))
# 创建 SimpleDialog 对象,并设置位置
MyDialog(root).geometry(f"+{x}+{y}")
root.mainloop()
```
以上示例代码中,`MyDialog` 是继承自 `SimpleDialog` 的自定义对话框类,通过计算鼠标位置和屏幕大小来确定对话框的位置,并将位置作为参数传递给 `geometry` 方法来设置对话框的位置。
阅读全文
相关推荐














