tkinter的canvas
时间: 2023-09-01 09:09:31 浏览: 166
Tkinter中的Canvas控件是用于绘图的控件,类似于HTML5中的Canvas。它可以用来绘制直线、圆形、弧形、矩形、字符串、图片等。创建Canvas控件的方式是调用tkinter.Canvas函数,并指定其属性,如背景色、宽度、高度、状态等。常用的属性有background(bg)、width、height、state、relief、borderwidth(bd)等。\[2\]
例如,下面的代码演示了创建一个包含空白Canvas控件的窗口,并设置了Canvas的背景色、宽度和高度:
```python
import tkinter as tk
window = tk.Tk()
window.title('Canvas测试')
window.geometry('400x300')
tk.Label(window, text='Canvas示例').grid(row=0, column=0)
cv = tk.Canvas(window, bg="lightblue", width=200, height=200)
cv.grid(row=1, column=1)
window.mainloop()
```
在Canvas控件上绘制图形可以使用create_oval、create_line、create_rectangle等方法。例如,下面的代码演示了在Canvas上绘制一个小圆点,并通过绑定鼠标左键事件实现随鼠标移动绘制圆点的功能:
```python
from tkinter import *
root = Tk()
w = Canvas(root, width=500, height=400)
w.pack()
def paint(event):
x1, y1 = (event.x - 1), (event.y - 1)
x2, y2 = (event.x + 1), (event.y + 1)
w.create_oval(x1, y1, x2, y2, fill='red')
# 绑定鼠标左键事件
w.bind('<B1-Motion>', paint)
# 创建一个按钮清除画板
Button(root, text='CLEAR', command=lambda x=ALL:w.delete(x)).pack(side=BOTTOM)
Label(root, text='Please hold the mouse button and move!').pack(side=BOTTOM)
mainloop()
```
以上是关于Tkinter中Canvas控件的简单介绍和示例代码。希望对你有帮助!
#### 引用[.reference_title]
- *1* *2* [Python中Tkinter模块的Canvas控件使用学习(1:基本用法)](https://blog.csdn.net/gc_2299/article/details/126532878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [tkinter-Canvas详解](https://blog.csdn.net/peanutfish/article/details/123226871)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文