问题
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.
回答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).
来源:https://stackoverflow.com/questions/41982824/python-tkinter-menu-creation-not-working