如何使用 customtkinter 从标签中删除 CTKLabel?

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

提问人:Pandas INC 提问时间:10/24/2023 更新时间:10/24/2023 访问量:53

问:

我有这个代码:

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

当我在上面运行应用程序时,我会得到一个“CTkLabel”,其中随机名称会消失 如何使该标签永远不会出现?

另外,有没有办法让我的列表完成后,它会重新启动?我添加了销毁函数,因为我不知道这是否可行。任何帮助将不胜感激。

image reference

python tkinter while-loop 标签 customtkinter

评论

1赞 acw1668 10/24/2023
设置为覆盖默认值 。也不是必需的,因为已经是可以直接访问的全局变量。text="""CTkLabel"label = app.winfo_children()[0]label
0赞 Pandas INC 10/24/2023
如果更改 text=“” 什么都不显示,另一部分谢谢没有抓住 IR
0赞 acw1668 10/24/2023
只需在创建标签时设置即可。text=""
0赞 Pandas INC 10/24/2023
我明白你的意思了,是的,有效,谢谢

答:

1赞 acw1668 10/24/2023 #1

由于选项的默认值是 ,因此如果未给出选项,则会显示该选项。如果您不想显示任何内容,只需设置为覆盖默认值。textCTkLabel"CTkLabel"texttext=""

如果已选择所有名称,要重新启动随机选择,您需要在从以下位置获得随机选择之前清除:chosen_namesnames

...

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="")
...