# 按键移动方块
from tkinter import *
class App():
def __init__(self, root):
self.root = root
self.root.geometry("500x500")
self.cv = Canvas(self.root, background="white")
self.cv.grid(row=0, column=0, sticky="news")
self.rectId = self.cv.create_rectangle(10, 10, 100, 50, fill='red', outline='blue', tags=('rect_1'))
self.polyId = self.cv.create_polygon(100, 100, 180, 100, 180, 200, 150, 200, 150, 130, 100, 130, fill='yellow', outline='blue')
# 下面这两步(按住左键和移动)写在一起,就相当于监测鼠标左键是否被按住和移动了,也就是实现了你所说的"连续事件"
# self.root.bind("<Button-1>", self.save_pos)
# self.root.bind("<B1-Motion>", self.add_line_or_do_sth)
# self.root.bind("<Right>", self.save_pos)
self.root.bind("<Right>", self.add_line_or_do_sth)
self.root.bind("<Left>", self.go_left)
self.root.bind("<Down>", self.go_down)
# self.root.bind("<KeyRelease>", self.add_line_or_do_sth) # 不需要按键释放检测
""" 注:要先激活tk窗口,才能操控! """
def save_pos(self, event):
# self.lastx, self.lasty = event.x, event.y
pass
def add_line_or_do_sth(self, event):
# self.cv.create_line((self.lastx, self.lasty, event.x, event.y))
# self.save_pos(event) # 光标移动了,当前位置就变成了"上一个位置"
# print(f"鼠标左键被按住了 并且发生了移动,目前光标位置为:({event.x},{event.y})")
# do something else you want
# ... 比如,把方块移动到新的位置上
print(self.cv.gettags(self.rectId), "正在右移...")
self.cv.move(self.rectId, 5, 0)
def go_left(self, event):
print(self.cv.gettags(self.rectId), "正在左移...")
self.cv.move(self.rectId, -5, 0)
def go_down(self, event):
print(self.cv.gettags(self.rectId), "正在下移...")
self.cv.move(self.rectId, 0, 5)
root = Tk()
app = App(root)
app.root.mainloop()