首页 > 解决方案 > 如何使用 tkinter 将用户选择的颜色分配给 Python 列表中的每个元素

问题描述

我正在尝试在图表上绘制信号。我需要一个功能,其中为用户选择的用于绘图的信号列表分配了用户自己选择的特定颜色。我需要在 Python 中使用 tkinter 生成这样一个 GUI 窗口,它允许我执行以下操作:

  1. 在一侧显示列表中存在的每个元素。
  2. 另一方面,一个颜色选择器供用户为该特定信号挑选和选择颜色。

PS编号。信号是动态的,因此每个信号的颜色选择器按钮也应该是动态的。

标签: pythontkinterdrop-down-menutkinter.optionmenu

解决方案


方法将是使用config(). 您可以使用以下代码更改元素的颜色:

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()

像这样,您可以设置任何元素的颜色。您还可以使用 更改元素的前景elementsname.config(fg=(color))

以下是一些网站链接,这些链接解释了如何自定义 Tkinter 小部件:


推荐阅读