在python tkinter中,我想让按钮消失并运行一个定义

时间:2017-08-17 13:04:34

标签: python python-3.x tkinter

我有一些代码,按下后会很乐意删除按钮,或者会运行代码,但我不能让它同时执行。我想知道是否还有这样做。

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

1 个答案:

答案 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()