2017-08-17 53 views
0

我有代碼,它會很高興地刪除按鈕後,它將被按下,或將運行代碼,但我不能使它們都做。我想知道是否有這樣做。在python tkinter中,我想做一個按鈕disapear,並運行一個定義

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

你是什​​麼意思「做這兩個」?如果要刪除按鈕並執行其他代碼,請將所有代碼封裝在函數中,並在按下按鈕時調用它。 –

+0

試圖把它放到一個功能之前,但它似乎並沒有工作 – notme21

回答

1

如果你想要做的是使用command執行definition,也拆除button,那麼你只需要簡單地調用command其去除button,同時執行任何代碼段,你需要它。

這僅僅需要正確使用lambda,讓您可以通過其中包含buttondefinition變量,就像下面:

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() 
+0

謝謝,這真的很有用 – notme21

+0

如果這回答你的問題,你可以標記答案爲其他用戶在未來看到接受? –

+0

請注意,這不會刪除按鈕,它只會使其不可見。 –

相關問題