简体   繁体   中英

How to assign user selected color to every element in a list in Python using tkinter

I am trying to plot signals on a graph. I need a feature where the list of signals selected by user for plotting is assigned a specific color chosen by the user himself. I need to generate such a GUI window using tkinter in Python which allows me to do :

  1. Show every element present in a list on one side.
  2. On the other side, a color chooser for the user to pick and choose color for that particular signal.

PS the no. of signals is dynamic, hence the color chooser buttons for each signal shall be dynamic too.

The approach will be to use config() . You can change the color of an element using the following code:

from tkinter import *
from tkinter import colorchooser

#Creating the window and setting it's size
root = Tk()
root.geometry("500x500")

#Function to show the color chooser
def choosecol(*args):
    global colorchosen
    colorchosen = colorchooser.askcolor(title="Choose color")

#Function to change the background color of the label.
def changecol(*args):
    lbl.config(bg=colorchosen[1])

#Creating the label which will change it's color
lbl = Label(root, text="My color will change.")
lbl.place(x=300, y=200)

#Button which will show the color chooser when clicked
btn = Button(root, text="Click me", command=choosecol)
btn.place(x=200, y=200)

#Button which will change the color to the color chosen using the previous button
changebtn = Button(root, text="Change color", command=changecol)
changebtn.place(x=200, y=250)

#Starting the window
root.mainloop()

Like this, you can set the color of any element. You can also change the element's foreground using elementsname.config(fg=(color)) .

Here are some more links to websites which explain how to customize the Tkinter widgets:

https://www.geeksforgeeks.org/how-to-add-a-border-color-to-a-button-in-tkinter/

https://www.geeksforgeeks.org/python-tkinter-label/

How to change the foreground or background colour of a Tkinter Button on Mac OS X?

https://www.tutorialspoint.com/python/tk_button.htm

https://www.dummies.com/programming/python/using-tkinter-widgets-in-python/

https://docs.python.org/3/library/tkinter.tix.html

Hope these help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM