如何在 Python tkinter 画布中删除线段?


画布小工具在 GUI 应用程序开发中有着许多用例。我们可以使用画布小工具来绘制形状、创建图形、图像以及许多其他内容。要在画布中绘制一条线段,我们可以使用 create_line(x,y,x1,y1, **options) 方法。在 Tkinter 中,我们可以绘制两种类型的线段 - 简单线段和虚线段。

如果你想要你的应用程序删除创建的线段,那么可以使用 delete() 方法。

示例

让我们来看一个示例,我们将删除在画布小工具中定义的线段。

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Define a function to delete the shape
def on_click():
   canvas.delete(line)

# Create a canvas widget
canvas=Canvas(win, width=500, height=300)
canvas.pack()

# Add a line in canvas widget
line=canvas.create_line(100,200,200,35, fill="red", width=10)

# Create a button to delete the button
Button(win, text="Delete Shape", command=on_click).pack()

win.mainloop()

输出

如果我们运行以上代码,它将显示一个包含一个按钮和一个在画布上形状的窗口。

现在,单击“删除形状”按钮从画布中删除显示的线段。

更新于: 06-8 月 -2021

3K+ 浏览次数

开启你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.