Python Tkinter菜单命令不起作用 [英] Python Tkinter Menu Command Not Working

查看:178
本文介绍了Python Tkinter菜单命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python 2.6.5中执行以下代码.我想做的是显示一个带有应用程序"菜单的主窗口.我希望菜单具有一系列应与Apps字典的键相对应的命令.当我单击命令时,我希望默认的Web浏览器打开并导航到Apps字典中该特定键的URL.相反,当我执行代码时,浏览器无需任何点击即可打开Apps字典中的第一个URL.请帮忙!

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()

推荐答案

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

调用函数的命令参数需要包装在lambda中,以防止立即调用它们.此外,绑定到for循环中的命令需要将循环变量作为默认参数,以便每次都绑定正确的值.

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]))

这篇关于Python Tkinter菜单命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆