首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >更新tkinter菜单项目的标签?

更新tkinter菜单项目的标签?
EN

Stack Overflow用户
提问于 2013-12-04 07:43:18
回答 3查看 10.5K关注 0票数 12

是否可以用tkinter更改菜单中项目的标签?

在下面的示例中,我希望将其从“示例项”( "File“菜单中)更改为不同的值。

代码语言:javascript
运行
复制
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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-12-04 08:08:26

我自己在Tcl手册中找到了解决方案

使用这样的entryconfigure()方法,该方法在单击该值后更改该值:

第一个参数1必须是要更改的项的索引,从1开始。

代码语言:javascript
运行
复制
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()
票数 11
EN

Stack Overflow用户

发布于 2015-06-29 17:11:17

我不知道在2.7上是否有不同,但在3.4上不再起作用了。

在python3.4中,您应该开始使用0计数条目,并使用entryconfig

代码语言:javascript
运行
复制
menu.entryconfig(0, label = "Clicked!")

http://effbot.org/tkinterbook/menu.htm

票数 6
EN

Stack Overflow用户

发布于 2017-12-19 12:04:58

检查这个动态菜单示例。这里的主要功能是您不需要关心菜单项的序列号(索引)。不需要跟踪菜单的索引(位置)。菜单项可以是第一个,也可以是最后一个,没关系。因此,您可以添加新的菜单,而没有索引跟踪(位置)的菜单。

代码在Python3.6上。

代码语言:javascript
运行
复制
# 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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20369754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档