2017-08-13 5 views
2

私はドロップダウンメニューを持っており、ログオフするにはオプションが必要です。ログオフを選択したときにメニューを閉じる必要がありますが、プログラム全体を閉じる必要はありません。Tkinterドロップダウンメニューを終了する

私はroot.quit()のようなメソッドを試しましたが、rootでも定義されていません。メニューを閉じる最善の方法は何ですか?メニューのためのコードは次のとおりです。

from tkinter import * 

def edit_or_retrieve(): 

    root = Tk() 
    root.title("Main Menu") 

    menu = Frame(root) 
    menu.pack(pady = 5, padx = 50) 
    var = StringVar(root) 

    options = [ 
     'Enter', 
     'Edit', 
     'Retrieve', 
     'Report 1 - Dates of birth', 
     'Report 2 - Home phone numbers', 
     'Report 3 - Home addresses', 
     'Log off', 

] 
    option = OptionMenu(menu, var, options[0], *options, command=function) 

    var.set('Select') 

    option.grid(row = 1, column = 1) 

    root.mainloop() 



def function(value): 
    if value == 'Edit': 
     edit() 
    if value == 'Enter': 
     enter() 
    if value == 'Retrieve': 
     display() 
    if value == 'Report 1 - Dates of birth': 
     reportone() 
    if value == 'Report 2 - Home phone numbers': 
     reporttwo() 
    if value == 'Report 3 - Home addresses': 
     reportthree() 
    if value == 'Log off': 
     #this is where the command or function name needs to go, 
     #however I am not sure what it should be. 
+2

ルート変数持つ関数[スコープ](http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html)のみ:以下

は、修正を加えたコードがこれを行うことです – SmartManoj

答えて

2

function()root.quit()を呼び出すと、問題は、それがedit_or_retrieve()関数にローカル変数だという事実によって引き起こされました。これは引数として渡して修正することができますfunction()、残念ながら、OptionMenuウィジェットはこれを行うものであり、変更することはできません。

あなたがこの問題を回避し、ソフトウェア "shim"として機能し、それがと呼ばれています function()への追加の引数を渡す短いlambda機能を作成することによって、関数に追加の引数を渡すことができますしかし

from tkinter import * 

def edit_or_retrieve(): 
    root = Tk() 
    root.title("Main Menu") 

    menu = Frame(root) 
    menu.pack(pady=5, padx=50) 
    var = StringVar(root) 

    options = ['Enter', 
       'Edit', 
       'Retrieve', 
       'Report 1 - Dates of birth', 
       'Report 2 - Home phone numbers', 
       'Report 3 - Home addresses', 
       'Log off',] 

    option = OptionMenu(menu, var, *options, 
         # use lambda to pass local var as extra argument 
         command=lambda x: function(x, root)) 

    var.set('Select') 
    option.grid(row=1, column=1) 

    root.mainloop() 

def function(value, root): # note added "root" argument 
    if value == 'Edit': 
     edit() 
    if value == 'Enter': 
     enter() 
    if value == 'Retrieve': 
     display() 
    if value == 'Report 1 - Dates of birth': 
     reportone() 
    if value == 'Report 2 - Home phone numbers': 
     reporttwo() 
    if value == 'Report 3 - Home addresses': 
     reportthree() 
    if value == 'Log off': 
     root.quit() 

edit_or_retrieve() 
+0

user8435959:これで問題は解決しないのですか?もしそうなら、それを受け入れてください。 「誰かが私の質問に答えるとどうすればいいですか?」(http://stackoverflow.com/help/someone-answers) – martineau

関連する問題