LanYu
LanYu

Reputation: 43

How to get tkinter menubar label Value?

I have looked a lot but can`t find the answer, below is an example:

Menu.add_command(label='abc',command=callback)

How can I get this 'abc' for variable?

Upvotes: 3

Views: 4723

Answers (2)

toyota Supra
toyota Supra

Reputation: 4537

I solved ur problem. Try this:

from tkinter import *

def callback(menu):
    for index in range(0,1): print( menu.entrycget(0, "label"))
    
def callback1(menu1):
    for index in range(1, 2): print( menu1.entrycget(1, "label"))
    
def callback2(menu):
    for index in range(2,3): print( menu.entrycget(2, "label"))
    
def callback3(menu):
    for index in range(3,4): print( menu.entrycget(3, "label"))
    
def callback4(menu):
    for index in range(4,4): print( menu.entrycget(4, "label"))
    
root = Tk() 
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=lambda: callback(filemenu))
filemenu.add_command(label="Open", command=lambda: callback1(filemenu))
filemenu.add_command(label="Save", command=lambda: callback2(filemenu))
filemenu.add_command(label="Save as...", command=lambda: callback3(filemenu))
filemenu.add_command(label="Close", command=None)

root.config(menu=menubar)
root.mainloop()

Upvotes: 1

Andath
Andath

Reputation: 22724

You can use entrycget() and pass to it the "label" option.

Here is a short example to demonstrate how it works:

import tkinter as tk


def callback(menu):
    x= menu.entrycget(0, "label")
    print(x) # This will print "abc" in your Terminal


root = tk.Tk()
menu_bar = tk.Menu(root)
file_menu = tk.Menu(menu_bar, tearoff=False)
file_menu.add_command(label="abc", command=lambda: callback(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()

Upvotes: 7

Related Questions