在pythontkinter中,我想创建一个按钮disapear并运行defin

2024-04-27 13:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有代码,将高兴地删除按钮后,按下它,或将运行代码,但我不能让它做这两个。我想知道是否有什么办法来做这件事。你知道吗

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

Tags: the代码texttruetkinterrunscodebutton
1条回答
网友
1楼 · 发布于 2024-04-27 13:15:03

如果您只想使用command来执行definition,同时删除button,那么您只需要调用command,它删除button,并执行您需要的任何代码段。你知道吗

这只需要正确使用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()

相关问题 更多 >