0

I am new to programming and am trying to create a menu in Python with the Tkinter package. But whenever I run the script in IDLE, all that is displayed is the top level (root) window.

Here is my script:

from tkinter import *
from tkinter import ttk

root.option_add('*tearOff', False)

menubar1 = Menu(root)
root.configure(menu = menubar1)
file = Menu(menubar1)
edit = Menu(menubar1)
help_ =  Menu(menubar1)
tools = Menu(menubar1)
other = Menu(menubar1)

menubar1.add_cascade(menu = file, label = 'File')
menubar1.add_cascade(menu = edit, label = 'Edit')
menubar1.add_cascade(menu = help_, label = 'Help')
menubar1.add_cascade(menu = tools, label = 'Tools')
menubar1.add_cascade(menu = other, label = 'Other')

Any idea why?

Thanks in advance.

5
  • 3
    The code you posted wouldn't even run, as it's missing the tkinter.Tk instance (probably saved in root) and the root.mainloop. If I add those parts, it shows up fine for me. Commented Feb 1, 2017 at 15:01
  • the answer is so small it should even get a defined answer just a comment Commented Feb 1, 2017 at 15:06
  • did you try run it without IDLE ? IDLE was created with tkinter so sometimes can be conflict. But IDLE is only tool to develop code and when code is ready then you don't use IDLE to run it. Commented Feb 1, 2017 at 20:02
  • TidB, what do you mean the tkinter.Tk instance? Commented Feb 3, 2017 at 15:17
  • See my answer (basically, Tk() defines your root: root = tkinter.Tk()) Commented Mar 1, 2017 at 19:06

1 Answer 1

1

As comments have pointed out, it's surprising that your code worked at all: root is not defined before you try to use option_add on it, so it will trigger NameError: name 'root' is not defined.

But it will work if you define it. Someone's already commented with the solution. The tkinter.Tk instance is how you define your root to create a window in the first place. mainloop() is what you do to maintain that window. It's even easier than it sounds:

from tkinter import *
import tkinter as tk # you could just say 'import tkinter', but 'tk' is easier to type

root = tk.Tk() # or, as @TidB mentioned, tkinter.Tk() if you're importing it as it is

root.option_add('*tearOff', False)
# insert all your code....
# and so on...
menubar1.add_cascade(menu = other, label = 'Other')

root.mainloop() # keeps the window up

Basically, just add mainloop() and Tk().

Also, since from tkinter import * naturally imports everything, you almost certainly do not need from tkinter import ttk (your second line of code).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.