0

I am trying to execute the following code in Python 2.6.5. What I want to do is show a main window with an 'Applications' menu. I want the menu to have a series of commands which should correspond to the keys of the Apps dictionary. When I click the command, I would like the default web browser to open and navigate to the url in the Apps dictionary for that particular key. Instead, when I execute the code the browser is opening to the first url in the Apps dictionary without any clicking. Help please!

from Tkinter import *
import webbrowser

#Real links are to pages on Intranet.
Apps={
     'Google':'http://www.google.com/',
     'Yahoo':'http://www.yahoo.com/'
     }

def openApp(appURL):
     webbrowser.open(appURL, new=1, autoraise=1)
     return None

root=Tk()
menubar=Menu(root)
root.config(menu=menubar)
appsMenu=Menu(menubar)
for app in Apps:
     appsMenu.add_command(label=app, command=openApp(Apps[app]))
menubar.add_cascade(label='Apps', menu=appsMenu)
root.mainloop()

1 Answer 1

4
 appsMenu.add_command(label=app, command=openApp(Apps[app]))

Command parameters that call functions need to be wrapped in a lambda, to prevent them from being called right away. Additionally, commands bound within a for loop need the looping variable as a default argument, in order for it to bind the right value each time.

 appsMenu.add_command(label=app, command=lambda app=app: openApp(Apps[app]))
Sign up to request clarification or add additional context in comments.

1 Comment

Kevin, thanks for the reply. I am new to Python and programming, and I really appreciate the help. Your solution works beautifully!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.