使用colorchooser模組更改tkinter視窗的背景顏色
Tkinter 提供了各種模組和類庫,我們可以用它們建立功能齊全的應用程式。Tkinter 還提供小部件來構建應用程式的元件和框架。Tkinter 中的 **colorchooser** 模組就是其中之一,它提供大量的顏色,以便使用者可以根據自己的喜好選擇和設定小部件的背景顏色。
要在你的應用程式中新增 **colorchooser** 功能,你首先需要使用 **"from tkinter import colorchooser"** 將此模組匯入到你的程式中。接下來,使用 **colorchooser.askuser()** 建立一個變數來顯示調色盤。
由於調色盤中的所有顏色都按索引編號進行索引和分離,你可以指定顏色應從哪個元組開始。最後,將背景顏色與給定變數一起使用以更改任何小部件的顏色。
示例
讓我們透過一個例子來理解這一點。
# Import the library from tkinter import * from tkinter import colorchooser # Create an instance of window win=Tk() # Set the geometry of the window win.geometry("700x350") # Create a label widget label=Label(win, text="This is a new Label text", font=('Arial 17 bold')) label.place(relx=0.5, rely=0.2, anchor = CENTER) # Call the function to display the color palette color=colorchooser.askcolor() # Initialize the color range by picking up the first color colorname=color[1] # Configure the background color win.configure(background=colorname) win.mainloop()
輸出
執行以上程式碼將顯示一個帶有標籤小部件和調色盤的視窗,要求使用者選擇顏色。
所選顏色將反映在視窗的背景顏色中。
廣告