How would I remove the CTKLabel from a label using customtkinter?

342 Views Asked by At

I have this code:

import customtkinter
import random

customtkinter.set_appearance_mode("light")

# Create a list to track the names that have already been chosen
chosen_names = []

def button_callback():
    # Create a list of names
    names = ["Alice", "Bob", "Carol", "Dave", "Eve"]

    # Randomly select a name from the list
    name = random.choice(names)

    # Check if the name has already been chosen
    while name in chosen_names:
        name = random.choice(names)

    # Add the name to the list of chosen names
    chosen_names.append(name)

    # Get the label
    label = app.winfo_children()[0]
    # Update the label text
    label.configure(text=name)
    label.grid_remove()

    # Check if all the values in the list have been selected
    if len(chosen_names) == len(names):
        app.destroy()

app = customtkinter.CTk()
app.title("Randomizer")
#replace with image
app.iconbitmap('isologo.ico')
app.geometry("500x500")

# Create a label
label = customtkinter.CTkLabel(app)
label.pack(padx=0, pady=0)

button = customtkinter.CTkButton(app, text="Selector Nombre", command=button_callback)
button.pack(ipadx=20, ipady=20,padx=20, pady=50)

app.mainloop()

When I run the app on top, I get a "CTkLabel" where the random names would go How would I make that label never appear?

Also, is there a way so that when my list finishes, it restarts? I added the destroy function because I don't know if this is possible. Any help would be appreciated.

image reference

1

There are 1 best solutions below

0
acw1668 On BEST ANSWER

As the default value of the text option of CTkLabel is "CTkLabel", so it will be shown if text option is not given. Just to set text="" to override the default value if you don't want to show anything.

To restart the random selection if all the names have been selected, you need to clear chosen_names before getting a random choice from names:

...

def button_callback():
    # Create a list of names
    names = ["Alice", "Bob", "Carol", "Dave", "Eve"]

    # Check if all the values in the list have been selected
    if len(chosen_names) == len(names):
        # clear chosen_names to restart
        chosen_names.clear()

    # Randomly select a name from the list
    name = random.choice(names)
    # Check if the name has already been chosen
    # or the same as the current one
    while name in (chosen_names or [label.cget("text")]):
        name = random.choice(names)
    # Add the name to the list of chosen names
    chosen_names.append(name)

    # Update the label text
    label.configure(text=name)
    label.grid_remove()

...

# set text="" to override the default value "CTkLabel"
label = customtkinter.CTkLabel(app, text="")
...