我有一些代码,按下后会很乐意删除按钮,或者会运行代码,但我不能让它同时执行。我想知道是否还有这样做。
import tkinter
window = tkinter.Tk()
def start():
gamestart = True
#this runs the code at the end
#btn = tkinter.Button(window, text = 'Prepare to fight' , command = start)
#this would create a button that runs the code(but not perfectly)
btn = tkinter.Button(window, text="Prepare to Fight", command=lambda: btn.pack_forget())
#this creates a button that dissapears
btn.pack()
#creates button
window.mainloop()
if gamestart == True:
lbl = tkinter.Label(window, text = 'WELCOME TO PYTHON COMBAT')
#beggining of game
答案 0 :(得分:1)
如果您只想使用command
执行definition
并删除button
,则只需拨打command
即可删除button
{1}}并执行您需要的任何代码段。
这只需要正确使用lambda
即可将包含button
的变量传递给definition
,如下所示:
from tkinter import *
root = Tk()
def command(button):
button.pack_forget()
print("Command executed and button removed")
button = Button(root, text="Ok", command=lambda:command(button))
button.pack()
root.mainloop()
上述内容只会“隐藏”button
意味着您可以稍后再次pack
,以下内容将完全删除button
:
from tkinter import *
root = Tk()
def command(button):
button.destroy()
print("Command executed and button removed")
button = Button(root, text="Ok", command=lambda:command(button))
button.pack()
root.mainloop()