如何在 Tkinter 畫布中將線從虛線改成實線?


Canvas 小部件是 Tkinter 應用程式中最常用的圖形表示小工具之一。要在 Canvas 小工具中顯示線條,我們可以使用內建庫方法 create_line(x1,y1,x2,y2, **options)

我們還可以使用 dash 屬性指定線條型別。要將線條型別從實線動態更改為 dash,可以使用 configure() 方法。透過將一個空值傳遞給 dash 屬性,我們可以從 實線 更改為 dash

範例

讓我們舉個例子來看看它是如何工作的。

# Import the required libraries
from tkinter import *
from tkinter import ttk

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

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

def update_line():
   canvas.itemconfig(line, dash=())

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

# Create a line
canvas.create_line(300, 30, 300, 150, dash=(4, 2), width=5)

# create a button to change the dash property of the line
ttk.Button(win, text="Change", command=update_line)

win.mainloop()

輸出

如果我們執行上面的程式碼,它將在 Canvas 小部件內顯示一條虛線。

更新時間: 2021 年 8 月 5 日

499 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.