如何在動態改變 tkinter 畫布的背景顏色?
畫布控制元件是 Tkinter 中最有用的控制元件之一。它具有各種功能和特性,可幫助開發人員根據其需要自定義應用程式。畫布控制元件用於在應用程式中顯示圖形。你可以建立不同型別的形狀並使用畫布控制元件繪製物件。
若要更改畫布控制元件的背景顏色,可以使用 configure() 方法。在這裡,你可以明確指定要更改的畫布控制元件的背景顏色。
範例
在以下示例中,我們建立了一個預設背景顏色為“天藍色”的畫布控制元件,可以在其建立後更改它。
# Import the required libraries from tkinter import * # Create an instance of tkinter frame win= Tk() # Define the size of the window win.geometry("700x300") # Function to change the color of the canvas def change_color(): canvas.configure(bg='blue') # Create a canvas widget canvas= Canvas(win, bg='skyblue') canvas.pack() # Create a button button=Button(win, text= "Change Color", font=('Helvetica 10 bold'), command=change_color) button.pack() win.mainloop()
輸出
它將產生以下輸出 −
單擊“更改顏色”按鈕將更改畫布的背景顏色。
廣告