创建一个简单窗口, 按下鼠标左键,同时按下键盘上的ctrl键,拖动鼠标,在用户区上画出一个矩形,矩形左上角以初始按下鼠标的点,右下角为鼠标当前位置,放开鼠标,窗口用户区显示一个最后的矩形。按下键盘的‘l’(英文字母L的小写),矩形放大,按下‘s’键,矩形缩小,并能用方向键实现所画矩形按相应方向移动。
时间: 2023-05-22 07:04:18 浏览: 83
跨屏协作鼠标按键映射_ahk_miui+窗口自定义大小、右键后退_中键回到桌面_miui+键盘映射_miui+右键后退_
可以使用以下代码来创建简单窗口并绘制矩形:
```
import tkinter as tk
class RectDrawer:
def __init__(self):
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, bg="white")
self.canvas.pack(fill=tk.BOTH, expand=1)
self.is_drawing = False
self.rect = None
self.init_pos = None
self.canvas.bind("<Button-1>", self.on_left_click)
self.canvas.bind("<B1-Motion>", self.on_dragging)
self.canvas.bind("<ButtonRelease-1>", self.on_left_release)
self.canvas.focus_set()
self.canvas.bind("<Key>", self.on_key_press)
def on_left_click(self, event):
if event.state & 0x4: # Check if Ctrl key is pressed
self.is_drawing = True
self.init_pos = (event.x, event.y)
def on_dragging(self, event):
if self.is_drawing:
x0, y0 = self.init_pos
x1, y1 = event.x, event.y
if self.rect:
self.canvas.delete(self.rect)
self.rect = self.canvas.create_rectangle(
x0, y0, x1, y1, outline="black")
def on_left_release(self, event):
if self.is_drawing:
self.is_drawing = False
x0, y0 = self.init_pos
x1, y1 = event.x, event.y
if self.rect:
self.canvas.delete(self.rect)
self.rect = self.canvas.create_rectangle(
x0, y0, x1, y1, outline="black", fill="white")
def on_key_press(self, event):
if event.char.lower() == "l": # Enlarge the rectangle
if self.rect:
coords = self.canvas.coords(self.rect)
x0, y0, x1, y1 = coords
self.canvas.delete(self.rect)
self.rect = self.canvas.create_rectangle(
x0-10, y0-10, x1+10, y1+10, outline="black", fill="white")
elif event.char.lower() == "s": # Shrink the rectangle
if self.rect:
coords = self.canvas.coords(self.rect)
x0, y0, x1, y1 = coords
self.canvas.delete(self.rect)
self.rect = self.canvas.create_rectangle(
x0+10, y0+10, x1-10, y1-10, outline="black", fill="white")
elif event.keysym in ("Up", "Down", "Left", "Right"): # Move the rectangle
if self.rect:
coords = self.canvas.coords(self.rect)
dx, dy = 0, 0
if event.keysym == "Up":
dy = -10
elif event.keysym == "Down":
dy = 10
elif event.keysym == "Left":
dx = -10
elif event.keysym == "Right":
dx = 10
x0, y0, x1, y1 = coords
self.canvas.delete(self.rect)
self.rect = self.canvas.create_rectangle(
x0+dx, y0+dy, x1+dx, y1+dy, outline="black", fill="white")
def run(self):
self.root.mainloop()
if __name__ == "__main__":
app = RectDrawer()
app.run()
```
当用户按下鼠标左键加上Ctrl键时,程序会记录下初始位置。当用户拖动鼠标时,程序不断更新矩形的位置和大小。当用户松开鼠标时,程序最终确定矩形的位置和大小。当用户按下键盘上的'l'键时,程序会把矩形放大。当用户按下's'键时,程序会把矩形缩小。当用户按下方向键时,程序会把矩形按相应方向移动。
阅读全文