您可以使用鼠标事件<Motion>
和<Button-1>
, (和其他)来运行将更改窗口内容的函数。
编辑:示例展示了如何bind()
使用鼠标运行函数以及如何计算diff_x
、diff_y
移动对象。您必须使用自己的函数bind()
来 diff_x
移动diff_y
POVRay 相机并渲染新图像。然后你将不得不替换画布上的图像。但我将使用画布对象而不是 POVRay 来展示鼠标移动时它如何改变。
此示例在移动鼠标时移动矩形,并在单击按钮时更改颜色。
但是您可以运行移动、缩放或旋转渲染图像的功能。
import tkinter as tk
# --- functions ---
def move_item(event):
canvas.coords(item, event.x-50, event.y-50, event.x+50, event.y+50)
def change_item(event):
if canvas.itemcget(item, 'fill') == 'red':
canvas.itemconfig(item, fill='blue')
else:
canvas.itemconfig(item, fill='red')
# --- main ---
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=300)
canvas.pack()
item = canvas.create_rectangle(0, 0, 100, 100, fill='red')
canvas.bind("<Button-1>", change_item)
canvas.bind("<Motion>", move_item)
root.mainloop()
编辑:使用<B1-Motion>
, <Shift-B1-Motion>
,<Control-B1-Motion>
移动对象的示例:
- 各个方向(
left mouse button
),
- 仅水平 (
Shift
+ left mouse button
)
- 仅垂直(
Control
+ left mouse button
)。
代码:
import tkinter as tk
# --- functions ---
def move_item(event):
global old_x
global old_y
diff_x = event.x - old_x
diff_y = event.y - old_y
for item in items:
canvas.move(item, diff_x, diff_y)
old_x = event.x
old_y = event.y
def move_horizontal(event):
global old_x
diff_x = event.x - old_x
for item in items:
canvas.move(item, diff_x, 0)
old_x = event.x
def move_vertical(event):
global old_y
diff_y = event.y - old_y
for item in items:
canvas.move(item, 0, diff_y)
old_y = event.y
def save_position(event):
global old_x
global old_y
old_x = event.x
old_y = event.y
# --- main ---
old_x = 0
old_y = 0
# init
root = tk.Tk()
# create canvas
canvas = tk.Canvas(root, width=500, height=300)
canvas.pack()
# create objects
items = [
canvas.create_rectangle(100, 100, 130, 130, fill='red'),
canvas.create_rectangle(200, 100, 230, 130, fill='blue'),
canvas.create_rectangle(100, 200, 130, 230, fill='yellow'),
]
canvas.bind("<Button-1>", save_position)
canvas.bind("<B1-Motion>", move_item)
canvas.bind("<Shift-B1-Motion>", move_horizontal)
canvas.bind("<Control-B1-Motion>", move_vertical)
# start program
root.mainloop()