用Python写一个Tkinter拖动控件改变控件的大小的demo
时间: 2024-05-08 10:18:00 浏览: 61
Python tkinter 下拉日历控件代码
5星 · 资源好评率100%
好的,这是一个关于Tkinter拖动控件改变大小的Python代码示例:
```python
import tkinter as tk
class ResizeableCanvas(tk.Canvas):
def __init__(self, parent, **kwargs):
tk.Canvas.__init__(self, parent, **kwargs)
self.bind("<Configure>", self.on_configure)
self.bind("<ButtonPress-1>", self.on_button_press)
self.bind("<B1-Motion>", self.on_button_move)
self.x_size = self.winfo_width()
self.y_size = self.winfo_height()
def on_configure(self, event):
self.x_size = event.width
self.y_size = event.height
def on_button_press(self, event):
self.startx = event.x
self.starty = event.y
def on_button_move(self, event):
self.newx = event.x
self.newy = event.y
diffx = self.newx - self.startx
diffy = self.newy - self.starty
self.config(width=self.x_size + diffx, height=self.y_size + diffy)
if __name__ == '__main__':
root = tk.Tk()
canvas = ResizeableCanvas(root, bg="white", highlightthickness=0)
canvas.pack(fill="both", expand=True)
rectangle = canvas.create_rectangle(50, 50, 250, 250, fill="blue")
root.mainloop()
```
以上代码可以创建一个可调整大小的画布(ResizeableCanvas),然后在该画布上绘制一个蓝色矩形。您可以尝试运行代码,并用鼠标拖动画布的边缘来调整画布的大小。
阅读全文