【问题标题】:How do I make a tkinter button destroy itself?如何让 tkinter 按钮自行销毁?
【发布时间】:2021-06-12 04:38:31
【问题描述】:

我在python的Tkinter中制作了这个程序,当代码运行时会弹出一个小窗口,然后会弹出一个开始按钮并使窗口全屏并显示之后的内容。我想让按钮在按下后自行销毁,以便全屏显示并删除按钮。我仍然是初学者,希望答案很简单。我正在寻找的解决方案可能是完全销毁按钮(首选)或在全屏窗口中将其移出视线。代码如下:

import Tkinter as w
from Tkinter import *

w = Tk()

w.geometry("150x50+680+350")
def w1():
    w.attributes("-fullscreen", True)
    l1 = Label(w, text = "Loaded!", height = 6, width = 8).pack()
    global b1
    b1.place(x = -10000, y = -10000)



b1 = Button(w, text = "Start", height = 3, width = 20, command = w1).place(x = 0, y = 10)
b2 = Button(w, text = "Exit", command = w.destroy).place(x = 1506, y = 0)

w.mainloop()

如你所见,我想让按钮 1 自行销毁。

【问题讨论】:

  • 更好的方案是隐藏按钮,以防你想把它恢复到原来的状态。您可以使用 b1.place_forget() 来做到这一点。
  • 另请阅读this。您的 b1b2 变量始终为 None

标签: python python-3.x user-interface tkinter button


【解决方案1】:

试试:

b1.place_forget()

这实际上会“忘记”按钮并将其隐藏起来。

编辑: 如果您收到 b1None 的错误,请尝试:

b1 = Button(w, text = "Start", height = 3, width = 20, command = w1)
b1.place(x = 0, y = 10)

您需要在底部添加b1.place() 选项才能使其工作

【讨论】:

  • 这行不通,会引发AttributeError: 'NoneType' object has no attribute 'place_forget'。您必须解决b1 始终为None 的问题
【解决方案2】:

试试这个:

import tkinter as tk # Use `import Tkinter as tk` for Python 2

root = tk.Tk()
root.geometry("150x50+680+350")

def function():
    global button_start
    root.attributes("-fullscreen", True)
    label = tk.Label(root, text="Loaded!", height=6, width=8)
    label.pack()
    button_start.place_forget() # You can also use `button_start.destroy()`



button_start = tk.Button(root, text="Start", height=3, width=20, command=function)
button_start.place(x = 0, y = 10)
button_exit = tk.Button(root, text="Exit", command=root.destroy)
button_exit.place(x=1506, y=0)

root.mainloop()

PS:请阅读this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2017-08-26
    • 2021-08-09
    相关资源
    最近更新 更多