python 获取鼠标实时位置并显示在GUI界面
时间: 2023-09-03 15:07:33 浏览: 74
可以使用Python的PyQt库来实现获取鼠标位置并在GUI界面中显示。
首先,需要导入PyQt库和PyQt的QtGui模块:
```python
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
```
然后,在GUI界面中创建一个标签用于显示鼠标位置:
```python
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 350, 200)
self.setWindowTitle('Mouse Position')
self.label = QLabel(self)
self.label.resize(250, 40)
self.label.move(50, 100)
```
接着,需要重写QWidget的`mouseMoveEvent`方法,以获取鼠标位置并更新标签的显示:
```python
def mouseMoveEvent(self, event):
x = event.x()
y = event.y()
text = f'x: {x}, y: {y}'
self.label.setText(text)
```
最后,创建应用程序并显示GUI界面:
```python
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
```
完整的代码如下:
```python
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 350, 200)
self.setWindowTitle('Mouse Position')
self.label = QLabel(self)
self.label.resize(250, 40)
self.label.move(50, 100)
def mouseMoveEvent(self, event):
x = event.x()
y = event.y()
text = f'x: {x}, y: {y}'
self.label.setText(text)
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)