简体   繁体   中英

Python 3.7 tkinter 8 - change a menu items 'command' option on the fly

I'm creating a tkinter application and trying to implement a model view controller pattern.

I have a View class:

class View(Frame):
    def __init__(self, master):
        """ Set up and display the user interface """
        Frame.__init__(self, master)
        self.menubar = Menu(master)
        self.menubar.add_command(label="Login")
        self.menubar.add_command(label="Register")
        self.menubar.add_command(label="Exit", command=master.quit)
        self.master = master
        self.master.config(menu=self.menubar)

and in my Controller I would like to set the 'command' option for menubar item 'Login' like so ( because I don't want my view handling login logic ):

class Controller:
    def __init__(self):
        self.root = Tk()
        self.model = Model()
        self.view = View(self.root)

---> self.view.menubar [set command for 'login' item = self.test() ] <-- The syntax here is what I am trying to figure out. Tkinter documentation is not very helpful and most blog posts offer very simplistic examples. I have tried something like: self.view.menubar.entryconfigure(0, command=self.test) but no luck.

    def run(self):
        self.root.title("Password Manager Application")
        self.root.mainloop()

    def test(self):
        print("Asdf")

Thanks for your help, Marc

Update: You can actually try using entryconfig(1, command=new_cmd)

An alternative approach you can do is to make these changes within the command function and place it in the controller code.

An example

def login_cmd(self):
    if self.login_cmd_option == 'A':
        self.login_A()
    else:
        self.login_B()

def set_login_cmd(login_cmd_option):
    self.login_cmd_option = login_cmd_option

The correct solution is to use itemconfigure . However, item zero may not be the item you think it is. If you don't set tearoff to False , item zero may be the tearoff item.

You can use the item's label instead of an number for the index, which guarantees the correct item is changed (assuming the label doesn't change).

Example:

self.view.menubar.entryconfigure("Login", command=self.test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM