python鼠標(biāo)拖拽功能怎么實(shí)現(xiàn)

小億
188
2023-12-01 19:11:16

在Python中,可以使用PyQt或Tkinter庫(kù)來(lái)實(shí)現(xiàn)鼠標(biāo)拖拽功能。

  1. 使用PyQt實(shí)現(xiàn)鼠標(biāo)拖拽功能:
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:  # 檢查是否為左鍵點(diǎn)擊
            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_())
  1. 使用Tkinter實(shí)現(xiàn)鼠標(biāo)拖拽功能:
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()

這些代碼創(chuàng)建了一個(gè)可拖拽的窗口小部件,并在鼠標(biāo)按下和移動(dòng)時(shí)更新部件的位置。

0