karan saxena
karan saxena

Reputation: 21

tkinter message box calling function

I want to display the title of the label in my messagebox which will display like "you have selected project". How can I do it with all of them like with save and exit also only using one function?

from tkinter import*

import tkinter.messagebox

root = Tk()

def func(label):
      tkinter.messagebox.askquestion("Information", "you have selected: ", label )


mymenu = Menu(root)
root.config(menu = mymenu)

submenu = Menu(mymenu)

mymenu.add_cascade(label = "file", menu = submenu)
submenu.add_command(label ="project", command = func)
submenu.add_command(label = "save", command = func)
submenu.add_separator()
submenu.add_command(label ="exit", command = func)

root.mainloop()

Upvotes: 0

Views: 1984

Answers (1)

j_4321
j_4321

Reputation: 16179

You can do it with lambda functions (for the submenu commands) and string formatting:

from tkinter import *

import tkinter.messagebox

root = Tk()

def func(label):
    tkinter.messagebox.askquestion("Information", "you have selected: {}".format(label))


mymenu = Menu(root)
root.config(menu = mymenu)

submenu = Menu(mymenu)

mymenu.add_cascade(label="file", menu=submenu)
submenu.add_command(label="project", command=lambda: func("project"))
submenu.add_command(label= "save", command=lambda: func("save"))
submenu.add_separator()
submenu.add_command(label="exit", command=lambda: func("exit"))

root.mainloop()

The lambda functions are used to pass the label argument corresponding to the submenu item to func.

For the messagebox, the syntax is tkinter.messagebox.askquestion(<title>, <message>), so you need to insert the label argument inside your message with string formatting: "you have selected: {}".format(label), th {} is replaced by the content of the label variable.

Upvotes: 2

Related Questions