You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Tkinter菜单栏中Help菜单右对齐、File菜单左对齐?

Tkinter菜单对齐:让Help菜单靠右,File菜单靠左

嘿,这个需求很好实现,只需要修改你添加Help菜单到主菜单的那一行代码,加上一个side='right'参数就搞定了。

关键修改步骤:

你原来添加Help菜单的代码是这样的:

my_menu.add_cascade(label = 'Help', menu = helpmenu)

把它改成下面这样:

my_menu.add_cascade(label = 'Help', menu = helpmenu, side='right')

修改后的完整代码:

from Tkinter import *
from ScrolledText import *
#dummy function to be changed later
def dummy():
    print 'Oont ooncha, oont ki peeth oonchi, neechi oonth ki poonch!'
#create your main window
root = Tk(className = 'Mere Bhains wala Editor')
#mera menu
my_menu = Menu(root)
#attach this menu to the the application
root.config(menu = my_menu)
#create my file menu
filemenu = Menu(my_menu)
filemenu.add_command(label = 'New', command = dummy)
filemenu.add_command(label = 'Open', command = dummy)
filemenu.add_separator()
filemenu.add_command(label = 'Save', command = dummy)
filemenu.add_command(label = 'Save as', command = dummy)
my_menu.add_cascade(label = 'File', menu = filemenu)
#create Help menu
helpmenu = Menu(my_menu)
helpmenu.add_command(label = 'Terms of use', command = dummy)
helpmenu.add_command(label = 'Documents', command = dummy)
helpmenu.add_command(label = 'FAQ', command = dummy)
helpmenu.add_separator()
helpmenu.add_command(label = 'Community discussions', command = dummy)
helpmenu.add_command(label = 'Report issue', command = dummy)
helpmenu.add_command(label = 'Search issues', command = dummy)
# 这里添加了side='right',让Help菜单靠右对齐
my_menu.add_cascade(label = 'Help', menu = helpmenu, side='right')
#create the scrolled text area
textpad = ScrolledText(root, width=640, height = 480)
textpad.pack()
# run the window as the application
root.mainloop()

为什么这样能行?

当Tkinter把Menu组件作为根窗口的菜单条使用时,add_cascade方法的side参数可以控制菜单项在菜单条上的位置。默认所有菜单项都会按添加顺序左对齐排列,而给Help菜单指定side='right'后,它就会被固定到菜单条的最右侧,File菜单则保持原来的左对齐状态,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Indian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:08:01