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

如何实现Tkinter按钮点击后自动销毁?(附概率游戏代码)

解决Tkinter点击按钮后隐藏所有按钮的问题

要实现点击任意按钮后所有按钮立即隐藏,核心是保存所有按钮的引用,这样才能批量操作它们的显示状态。以下是具体修改方案:

关键修改点

  • 新增全局列表存储所有按钮实例,避免创建按钮时覆盖变量
  • 在按钮点击后的逻辑中,遍历列表调用place_forget()隐藏所有按钮
  • 补充调用Start()函数,确保按钮正常显示

修改后的完整代码

from tkinter import *
from tkinter import messagebox
import random

point = 0
buttons = []  # 新增全局列表存储所有按钮

def showerror():
    messagebox.showerror("Loser","Next time :)")
    messagebox.showinfo("Your point", "Point: " + str(point))

def addpoint():
    global point
    point +=  31

def deleteButton():
    pass

def test():
    r = random.randint(0,7)
    if r > 4:
        showerror()
    elif r <= 4:
        addpoint()
    # 遍历所有按钮,调用place_forget()隐藏
    for btn in buttons:
        btn.place_forget()

tk = Tk()
tk.title("Are u Lucky")
tk.geometry("400x300")

def Start():
    P1 = Label(tk, text="Choose")
    P1.place(x=157,y=10)
    # 批量创建按钮并添加到列表
    positions = [
        (10,30), (50,30), (90,30), (130,30), (170,30),
        (210,30), (250,30), (290,30), (330,30), (370,30),
        (10,60), (50,60), (90,60), (130,60), (170,60),
        (210,60), (250,60), (290,60), (330,60), (370,60),
        (10,90), (50,90), (90,90), (130,90), (170,90),
        (210,90), (250,90), (290,90), (330,90), (370,90),
        (10,120), (50,120), (90,120), (130,120), (170,120),
        (210,120), (250,120), (290,120), (330,120), (370,120),
        (10,150), (50,150), (90,150), (130,150), (170,150),
        (210,150), (250,150), (290,150), (330,150), (370,150)
    ]
    for x, y in positions:
        btn = Button(tk, text="  X   ", command=test)
        btn.place(x=x, y=y)
        buttons.append(btn)  # 将按钮添加到全局列表

Start()  # 调用Start创建按钮

tk.mainloop()

补充说明

  • place_forget()只是隐藏按钮,后续还可以通过place()重新显示;如果要彻底销毁按钮,改用btn.destroy()即可
  • 把所有按钮位置整理成列表,简化了原代码的重复创建逻辑,更易维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:05:17