2017-08-13 108 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小部件就是這樣做的,你不能修改它。

但是,您可以解決此通過創建一個短lambda功能充當軟件"shim",並傳遞額外參數function()稱爲傳遞額外的參數給函數。

下面是與修改您的代碼來執行此:

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