代码之家  ›  专栏  ›  技术社区  ›  Pandas INC

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

  •  0
  • Pandas INC  · 技术社区  · 2 年前

    我有这个代码:

    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”,随机名称会放在那里。我该如何使该标签永远不会出现?

    还有,有没有办法在我的列表完成后重新启动?我添加了destroy函数,因为我不知道这是否可能。如有任何帮助,我们将不胜感激。

    image reference

    0 回复  |  直到 2 年前
        1
  •  1
  •   acw1668    2 年前

    作为的默认值 text 的选项 CTkLabel "CTkLabel" ,因此将显示 文本 未给出选项。只是为了设置 text="" 如果您不想显示任何内容,可以覆盖默认值。

    如果已选择所有名称,则要重新启动随机选择,需要清除 chosen_names 在从中随机选择之前 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="")
    ...