Skip to main content
 首页 » 编程设计

python之退出 Tkinter 下拉菜单

2024年10月01日9daizhj

我有一个下拉菜单,希望它必须有注销选项。我需要在选择注销时关闭菜单,但我不想关闭整个程序。

我已经尝试过像 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. 

请您参考如下方法:

调用root.quit()的问题在function()是因为它是 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()