user2975375
user2975375

Reputation: 81

How to make a label with the background color as a color chosen by the user?

So, here is my code. Essentially, what I want to do is to make a label with the background color the same as the color chosen in the color dialog, so that the person can see the color and the color hexadecimal code. Please help.

import sys
from tkinter import *
from tkinter import colorchooser

mGui = Tk()
mGui.geometry("600x300+500+500")
mGui.title("Hexadecimal Color Chooser")

def getColor():
    mycolor = colorchooser.askcolor()
    label = Label(mGui, bg = mycolor).pack()
    mycolor = str(mycolor)
    start = mycolor.index("#")
    stop = mycolor.index("')")
    mycolor = mycolor[start:stop]
    label = Label(mGui, text = "The hexadecimal color code is: " + mycolor).pack()

button = Button(mGui, text = "Choose a color", command = getColor).place(x=0, y=0)

Upvotes: 1

Views: 1018

Answers (1)

user2555451
user2555451

Reputation:

There are three issues here:

  1. Importing sys if you are not going to use it does nothing.

  2. The place, pack, and grid methods of Tkinter widgets always return None. Hence, any calls to them should always be placed on their own line.

  3. tkinter.colorchooser.askcolor returns a two-item tuple like this:

    ((128.5, 64.25, 64.25), '#804040')  
    

    Futhermore, the last item in this tuple is the hex code of the chosen color.

Below is a fixed version of the script:

from tkinter import *
from tkinter import colorchooser

mGui = Tk()
mGui.geometry("600x300+500+500")
mGui.title("Hexadecimal Color Chooser")

def getColor():
    color_choice = colorchooser.askcolor()[1]  # get the hex code
    color = Label(mGui, bg=color_choice)
    color.pack()
    hexcode = Label(mGui, text="The hexadecimal color code is: "+color_choice)
    hexcode.pack()

button = Button(mGui, text="Choose a color", command=getColor)
button.place(x=0, y=0)

mGui.mainloop()

Upvotes: 2

Related Questions