在Python中,可以使用PyQt或Tkinter庫來實現鼠標拖拽功能。
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class DraggableWidget(QWidget):
def __init__(self):
super().__init__()
self.setFixedSize(200, 200)
self.setWindowTitle('Draggable Widget')
self.draggable = False
self.offset = None
def mousePressEvent(self, event):
if event.button() == 1: # 檢查是否為左鍵點擊
self.draggable = True
self.offset = event.pos()
def mouseMoveEvent(self, event):
if self.draggable:
self.move(event.globalPos() - self.offset)
def mouseReleaseEvent(self, event):
if event.button() == 1: # 檢查是否為左鍵釋放
self.draggable = False
if __name__ == '__main__':
app = QApplication(sys.argv)
widget = DraggableWidget()
widget.show()
sys.exit(app.exec_())
import tkinter as tk
class DraggableWidget(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('200x200')
self.title('Draggable Widget')
self.draggable = False
self.offset = None
self.bind('<Button-1>', self.on_mouse_press)
self.bind('<B1-Motion>', self.on_mouse_move)
self.bind('<ButtonRelease-1>', self.on_mouse_release)
def on_mouse_press(self, event):
self.draggable = True
self.offset = (event.x, event.y)
def on_mouse_move(self, event):
if self.draggable:
x = self.winfo_pointerx() - self.offset[0]
y = self.winfo_pointery() - self.offset[1]
self.geometry(f'+{x}+{y}')
def on_mouse_release(self, event):
self.draggable = False
if __name__ == '__main__':
widget = DraggableWidget()
widget.mainloop()
這些代碼創建了一個可拖拽的窗口小部件,并在鼠標按下和移動時更新部件的位置。