You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter界面文本重置方法咨询:点击「Pick the Associate」按钮时重置文本并重新随机选取名字

Fixing Tkinter Name Picker: Reset & Clear Functionality

Got it, let's get your name picker working with proper reset behavior when clicking "Pick the Associate" again, and add the clear functionality to the "Clear" button. Here's the breakdown of changes and the updated code:

Key Issues in the Original Code

  • Every time you click "Pick the Associate", a new Label is created and stacked on top of the old one—we need to reuse a single label instead of spawning new ones.
  • The "Clear" button has no command bound to it, so it doesn’t do anything right now.
  • There’s a small typo: Len should be lowercase len, and you’re missing the random module import for randint (that would throw an error otherwise).

Updated Working Code

import random
from tkinter import Tk, Label, Button

root = Tk()
root.title('Pick the MOM')
root.geometry("500x500")

# Initialize the winner label once, outside the pick function so we can reuse it
winnerLabel = Label(root, text="", font=('helvetica', 18))
winnerLabel.pack(pady=50)

def pick():
    entries = ["Giovanni", "Francesca", "Martin", "Anderson", "Raj" , "Kinga"]
    # Convert to set + back to list to get unique entries (your list is already unique, but this keeps the logic intact)
    unique_entries = list(set(entries))
    # Generate random index for the winner
    rando = random.randint(0, len(unique_entries) - 1)
    # Reset the label's text first, then set the new winner
    winnerLabel.config(text=unique_entries[rando])

def clear_text():
    # Empty out the winner label's text
    winnerLabel.config(text="")

topLabel = Label(root, text="MOM Taker", font=('Helvetica', 24))
topLabel.pack(pady=20)

winButton = Button(root, text="Pick the Associate", font=("Helvetica", 24), command=pick)
winButton.pack(pady=20)

resetButton = Button(root, text="Clear", font=("Helvetica", 24), command=clear_text)
resetButton.pack(pady=20)

root.mainloop()

What We Changed

  • Added the missing import random and fixed the Len → len typo to avoid runtime errors.
  • Created winnerLabel once outside the pick function, so we can update its text instead of creating new labels every time.
  • In the pick function, we use winnerLabel.config(text=...) to overwrite the existing text—this automatically clears any previous name before showing the new one.
  • Added a clear_text function that resets the label to an empty string, and bound it to the "Clear" button’s command parameter so it actually does something when clicked.

Now when you click "Pick the Associate" again, it’ll replace the old name with the new one (no more stacked labels), and the "Clear" button will wipe the displayed text clean.

内容的提问来源于stack exchange,提问作者Praslea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:37:47