Following is a Python script to display a menu(file,option) where option is used to initiate a function conf.
As I had assumed, the conf fun will only execute when i press the respective menu widget.
That means ‘haha’ will only be printed when i press option/Edit comp list and similarly ‘nana’ will only be printed when i press option/Edit pvt list
However, as i start the script top.py, the ‘haha’ and ‘nana’ are printed with the start. That is because the conf function is executed two times at the start. This is unexpected. Please advice.
The error appears to be in following statements:
menu_option.add_command(label=”Edit Comp List”,command=conf(‘comp’))
menu_option.add_command(label=”Edit pvt List”,command=conf(‘pvt’))
Code:-
#File name :top.py
from Tkinter import *
import ttk
def conf(section):
if section == 'comp':
print 'haha'
if section == 'pvt':
print 'nana'
pass
root = Tk()
root.title("NRUNTEST GUI VERSION 1")
menuframe = Frame(root)
menuframe.grid(column=0,row=0)
menuframe.columnconfigure(0,weight=1)
menuframe.rowconfigure(0,weight=1)
buttonh = ttk.Button(root, text='Quit',command=root.quit)
buttonh.grid(row=2, column=2, sticky=(E,W))
menubar = Menu(menuframe)
menu_file = Menu(menubar, tearoff=0)
menu_option = Menu(menubar, tearoff=0)
menubar.add_cascade(menu=menu_file, label='File')
menubar.add_cascade(menu=menu_option, label='Option')
**menu_option.add_command(label="Edit Comp List",command=conf('comp'))**
menu_option.add_separator()
**menu_option.add_command(label="Edit pvt List",command=conf('pvt'))**
menu_file.add_separator()
root.config(menu=menubar)
root.mainloop()
Your error is quite simple:
When you pass this argument:
You aren’t actually passing it. You are passing the result of
conf('comp')as your function. The result of that function is aprintstatement, which is what you observe.Try making separate functions for each case and add the command like this: