2017-03-31 6 views
0

ボタンをクリックすると消えるボタンを表示しようとしています。その後、「戻る」ボタンをクリックすると、新しいボタンが消えて元のボタンが再び表示されます。他の機能で定義されているボタンを削除する

問題は、別の関数から情報を取得する方法を知らないことです。 search(event)関数のsearch_buttonに何かしようとすると、search_buttonはmain()関数でのみ定義されているため定義されていません。

import tkinter as tk 
window = tk.Tk() 
def search(event): 

    #insert "delete search_button" logic here 

    easy_button = tk.Button(window, text = "Easy") 
    easy_button.bind("<Button-1>", easy_search)  
    easy_button.pack() 

    back_button = tk.Button(window, text = "Back") 
    back_button.bind("<Button-1>", back_button1) #had to put 1 on end here. It seems back_button is predefined as an object 
    back_button.pack() 

def easy_search(event): 
    #does a bunch of stuff that doesn't matter for this question 
    pass 

def back_button1(event): 
    #this should delete easy_button and reinitiate search_button 
    pass 

def main(): 

    search_button = tk.Button(window, text = "Search") 
    search_button.bind("<Button-1>", search)  
    search_button.pack() 

main() 
window.mainloop() 

答えて

1

最も簡単な方法は、すべての機能が同じself名前空間を共有することがあった、クラスにすべてのものを作ることです。また、別の関数で押されたボタンをバインドする場合は、実際にイベントを使用していない限り、代わりに 'コマンド'を使用してください。

import tkinter as tk 
window = tk.Tk() 


class Search: 
    def __init__(self): 
     self.search_button = tk.Button(window, text = "Search") 
     self.search_button['command'] = self.search 
     self.search_button.pack() 
    def search(self): 
     self.search_button.pack_forget() # or .destroy() if you're never going to use it again 
     self.easy_button = tk.Button(window, text = "Easy") 
     self.easy_button['command'] = self.easy_search 
     self.easy_button.pack() 

     self.back_button = tk.Button(window, text = "Back") 
     self.back_button['command'] = self.back_button1 
     self.back_button.pack() 

    def easy_search(self): 
     #does a bunch of stuff that doesn't matter for this question 
     pass 

    def back_button1(self): 
    #this should delete easy_button and reinitiate search_button 
     pass 


widgets = Search() 
window.mainloop() 

ありますが、ウィジェットの破壊やpack_forgetコマンドを呼び出すことができます。これに一緒に来る

+0

ありがとうございました。それは役に立ちます:)。 バインドの代わりにコマンドを使用する理由を説明できますか? これまで私はこの問題が発生していたが、その違いについては混乱していた。 –

+0

コマンドを使用するのは、ユーザーがボタンをクリックしたかどうかだけを検出し、ユーザーが行ったときに何かを行う場合です。バインドの使用は通常より遅いですが、主な使い方は、画面上でユーザーがボタンを押した場所など、クリックの*イベント*を検出することです。イベントを使用しない場合は、コマンドのみを使用することをお勧めします。 – abccd

関連する問題