简体   繁体   English

如何使用 tkinter 创建菜单栏?

[英]How do I use tkinter to create a menubar?

This is my first post, so please give feedback to improve if need be.这是我的第一篇文章,所以如果需要,请提供反馈以改进。

I am following the tkinter tutorial on tkdocs to learn tkinter.我正在按照 tkdocs 上的tkinter教程学习 tkinter。 The current lesson is attempting to teach me how to create menus, but whenever I run their script, a separate window pops up instead of menu attached the the root window.当前课程试图教我如何创建菜单,但每当我运行他们的脚本时,都会弹出一个单独的窗口,而不是菜单附加到根窗口。

from tkinter import *
from tkinter import ttk


root = Tk()
root.option_add('*tearOff', FALSE)
win = Toplevel(root)
menubar = Menu(win)
win['menu'] = menubar

root.mainloop()

This pops up as a second window.这作为第二个窗口弹出。 I'm not sure if I am simply not understanding the material, or if I am doing something wrong.我不确定我是否根本不理解这些材料,或者我是否做错了什么。 The lessons are written in the mindset that you are using at least python 3 and tkinter 8.6.这些课程是在您至少使用 python 3 和 tkinter 8.6 的心态下编写的。 I have the current Anaconda distribution and it meets both of these requirements.我有当前的 Anaconda 发行版,它满足这两个要求。

What am I doing incorrectly to have this code open a separate window as opposed to a menu attached to a window?让此代码打开一个单独的窗口而不是附加到窗口的菜单我做错了什么?

I was able to figure out the issue.我能够弄清楚这个问题。 I misread the tutorial and expected a single window to open up with a menubar and a couple options within that menubar.我误读了教程,并希望打开一个窗口,其中包含一个菜单栏和该菜单栏中的几个选项。 After messing with the code, I was able to write a script that created the window I originally thought we were going to open.在弄乱了代码之后,我能够编写一个脚本来创建我最初认为我们要打开的窗口。 Ultimately, I didn't realize that "TopLevel" would open a separate window, so that was on me.最终,我没有意识到“TopLevel”会打开一个单独的窗口,所以这是我的责任。 Below is the code that I used to open up a window with the menubar.下面是我用来打开带有菜单栏的窗口的代码。

from tkinter import *
from tkinter import ttk

root = Tk()
root.option_add('*tearOff', FALSE)


menubar = Menu(root)
menu_file = Menu(menubar)
menu_edit = Menu(menubar)
menubar.add_cascade(menu=menu_file, label='File')
menubar.add_cascade(menu=menu_edit, label='Edit')
root['menu'] = menubar

root.mainloop()

Thanks, and I hope this helps someone else understand what is happening if they are learning tkinter as well.谢谢,我希望这可以帮助其他人了解正在学习 tkinter 的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM