是否可以用tkinter更改菜单中项目的标签?
在下面的示例中,我希望将其从“示例项”( "File“菜单中)更改为不同的值。
from tkinter import *
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: print('clicked!'))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()发布于 2013-12-04 08:08:26
我自己在Tcl手册中找到了解决方案
使用这样的entryconfigure()方法,该方法在单击该值后更改该值:
第一个参数1必须是要更改的项的索引,从1开始。
from tkinter import *
root = Tk()
menu_bar = Menu(root)
def clicked(menu):
menu.entryconfigure(1, label="Clicked!")
file_menu = Menu(menu_bar, tearoff=False)
file_menu.add_command(label="An example item", command=lambda: clicked(file_menu))
menu_bar.add_cascade(label="File", menu=file_menu)
root.config(menu=menu_bar)
root.mainloop()发布于 2015-06-29 17:11:17
我不知道在2.7上是否有不同,但在3.4上不再起作用了。
在python3.4中,您应该开始使用0计数条目,并使用entryconfig。
menu.entryconfig(0, label = "Clicked!")http://effbot.org/tkinterbook/menu.htm
发布于 2017-12-19 12:04:58
检查这个动态菜单示例。这里的主要功能是您不需要关心菜单项的序列号(索引)。不需要跟踪菜单的索引(位置)。菜单项可以是第一个,也可以是最后一个,没关系。因此,您可以添加新的菜单,而没有索引跟踪(位置)的菜单。
代码在Python3.6上。
# Using lambda keyword and refresh function to create a dynamic menu.
import tkinter as tk
def show(x):
""" Show your choice """
global label
new_label = 'Choice is: ' + x
menubar.entryconfigure(label, label=new_label) # change menu text
label = new_label # update menu label to find it next time
choice.set(x)
def refresh():
""" Refresh menu contents """
global label, l
if l[0] == 'one':
l = ['four', 'five', 'six', 'seven']
else:
l = ['one', 'two', 'three']
choice.set('')
menu.delete(0, 'end') # delete previous contents of the menu
menubar.entryconfigure(label, label=const_str) # change menu text
label = const_str # update menu label to find it next time
for i in l:
menu.add_command(label=i, command=lambda x=i: show(x))
root = tk.Tk()
# Set some variables
choice = tk.StringVar()
const_str = 'Choice'
label = const_str
l = ['dummy']
# Create some widgets
menubar = tk.Menu(root)
root.configure(menu=menubar)
menu = tk.Menu(menubar, tearoff=False)
menubar.add_cascade(label=label, menu=menu)
b = tk.Button(root, text='Refresh menu', command=refresh)
b.pack()
b.invoke()
tk.Label(root, textvariable=choice).pack()
root.mainloop()https://stackoverflow.com/questions/20369754
复制相似问题